This topic is locked

How to implement a custom dependent dropdown box

7/27/2025 10:06:09 PM
PHPRunner Tips and Tricks
Sergey Kornilov admin

We have an Edit page of products table and want to make CategoryID dropdown to be dependent on the value of UnitPrice field which is a text box. We want it to work a very specific way. If UnitPrice field is 5 or greater, we want to display categories that have 'a' in them. If price is below 5 then we want to show categories that have 't' in them. This example is completely made up for the purpose of this exercise.

Here is how it looks. You can see on this screenshot that the price is greater than 5 and all categories have 'a' in them.
img alt

To do so we have created a field event for the UnitPrice tied to 'change' event. Check the inline comments for additional info.

ClientBefore:

// simply pass the current value of UnitPrice to the Server event
params["value"] = this.getValue();

Server:

if ( $params["value"] > 5 ) {
$_SESSION["var"]="a";
} else {
$_SESSION["var"]="t";
}

// get the list of new categories from the server
// loop through the recordset adding all entries to a two-dimensional array $arr

$sql = DB::PrepareSQL("select CategoryID, CategoryName from categories where CategoryName like '%:1%'", $_SESSION["var"] );
$rs = DB::Query($sql);
$arr = array();
while( $data = $rs->fetchAssoc() ) {
$arr[] = $data;
}

// pass the array to ClientAfter event
$result["data"] = $arr;

ClientAfter:

// delete all existing elements from the CategoryID dropdown
$("select[id^='value_CategoryID'] option").remove();

// loop through results and add them one by one to the dropdown box
for (const record of result["data"]) {

$("select[id^='value_CategoryID']").append($('<option>', {
value: record["CategoryID"],
text: record["CategoryName"]
}));
}

This is it! Just make sure you use table and field names that match your database structure.