Click here for EduSec Demo EduSec Screenshots

Creating a dependent dropdown

On 2013-06-10 - By Ravi Thanki

Often you'll need a form with two dropdowns, and one dropdown's values will be dependent on the value of the other dropdown. Using Yii's built-in AJAX functionality you can create such a dropdown.


The view with the form.

echo CHtml::dropDownList(‘country_id’,”, array(1=>’USA’,2=>’France’,3=>’Japan’),
‘ajax’ => array(
‘type’=>’POST’, //request type
‘url’=>CController::createUrl(‘currentController/dynamiccities’), //url to call.
//Style: CController::createUrl(‘currentController/methodToCall’)
‘update’=>’#city_id’, //selector to update
//’data’=>’js:javascript statement’
//leave out the data key to pass all form values through

//empty since it will be filled by the other dropdown
echo CHtml::dropDownList(‘city_id’,”, array());

The controller action

It will have to output the html to fill the second dropdownlist. Furthermore it will do that dependent on the the value of the first dropdown.

public function actionDynamiccities()
array(‘:parent_id’=>(int) $_POST['country_id']));

foreach($data as $value=>$name)
echo CHtml::tag(‘option’,