Lets say we need user to select a year they will be working with when the logon to the application. We want to save this selected value to a session variablle and later use it on some pages to filter data.
Here is how it is going to look in the generated application.
- Proceed to the Login page in the Page Designer and insert a code snippet. Here is the code that pulls a list of unique years from orders tables and displays it as a dropdown box.
$sql = "select distinct year(OrderDate) as y from orders where OrderDate is not null order by 1";
echo "<select class='form-control' name='year' id='year'>";
echo "<option value=''>Select year</option>";
// main loop
$rs = DB::Query($sql);
while( $data = $rs->fetchAssoc() )
{
$year = $data["y"];
echo "<option value='". $year . "'>". $year . "</option>";
}
echo "</select>";- Now we need to make sure that the selected year value is submitted to the server side when user logs in. We will use a technique explained in this article. Luckily it works on the Login page as well.
The following code goes to Login page: Javascript OnLoad event:
this.on('beforeSave', function(formObj, fieldControlsArr, pageObj){
var val = $("#year").val();
formObj.baseParams['year'] = val;
});- On the server side we will read this dropdown box selected value from POST and save it to the session variable. We will also handle the situation when user didn't select any value from the dropdown box. Just making sure that this session variable is always populated.
The following code goes to Login page: Before Login event:
if ($_POST["year"]) {
$_SESSION["year"] = $_POST["year"];
} else {
$_SESSION["year"] = date('Y');
}
return true;- Now we can use session variable $_SESSION["year"] on any of the pages in your application. For instance, if we only want to display orders that belong to the selected year we can add the following code to Orders table: After Table Init event:
$query->addWhere("year(OrderDate) = ".$_SESSION["year"]);
This is it!