Use yii framework dropdown to create cascading menus
You often need a form, cascading cities, or cascading categories and other functions. There are two drop-down boxes, and the value of one depends on the other drop-down box. Using Yii's built-in ajax functionality, you can create such a drop-down box. How to implement this is demonstrated below.
The first is the view of the form. We will display a form that will display the country, and based on the country it will be displayed with the city.
Program codeProgram code
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan') ,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>'dynamiccities', //url to call
'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 first drop-down box consists of several value/name pairs representing countries composition. . When it is changed, an ajax request will be completed by the current controller's 'dynamiccities' action. The result of the request (the output of the 'dynamiccities' action) will be replaced with the dropdown box whose second id is #city_id.
Next is the controller action, which will output html to populate the second drop-down box. Also it will depend on the value of the first drop down box.
Program codeProgram code
public function actionDynamiccities()
{
$data=Location::model()->findAll('parent_id=:parent_id',
array(':parent_id'=> (int) $_POST['country_id']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{O echo chtml :: tag ('option',
array ('value' = & gt; $ value), chtml :: encode ($ name), true); Retrieve all cities whose parent_id is the first drop-down box value. All these cities will then be output into labels, ultimately forming a second drop-down box.
You might be wondering where $_POST['country_id'] comes from. Very simple, when the 'data' key of the ajax array in the first drop-down box is empty, the values of all elements of the form where the drop-down box is located will be passed to the controller through an ajax request. If you are using Firebug you can view this request.
This behavior can also be changed. By default, the value of the 'data' key in the ajax configuration array is js:jQuery(this).parents("form").serialize(). The js at the beginning: tells Yii that what follows is a javascript statement and should not be escaped. Therefore, if you change the 'data' key to another statement starting with 'js:', you can fill in your own statement. Also works with 'success' parameter.