Changes
Title
unchanged
Creating a dependent dropdown
Category
unchanged
Tutorials
Yii version
unchanged
Tags
changed
AJAX, drop down list
Content
changed
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.
Below will be demonstrated how you can achieve this.
First the view with the form.
The view with the form.
-----------------------
We'll show a form that shows countries and dependent of the country selected will show cities.
```php[...]
The first dropdown is filled with several value/name pairs of countries. Whenever it is changed an ajax request will be done to the 'dynamiccities' action of the current controller. The result of that request (output of the 'dynamiccities' action) will be placed in the second dropdown with id is #city_id.
Next is tThe controller action
, i
---------------------
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()
{
//please enter current controller name because yii send multi dim array
$data=Location::model()->findAll('parent_id=:parent_id',
array(':parent_id'=>(int) $_POST['
Current-Controller']['country_id']));
$data=CHtml::listData($data,'id','name');[...]
in the filters() Method. This will disable all access controls for the controller. You should always re-enable it after testing.
###Related Links
[Chinese version](http://www.itkuaixun.com/bbs/thread-202-1-1.html-------------
[Persian version](http://shgn.ir/%D8%A7%DB%8C%D8%AC%D8%A7%D8%AF-%D9%84%DB%8C%D8%B3%D8%AA-%D9%87%D8%A7%DB%8C-%D9%88%D8%A7%D8%A8%D8%B3%D8%AA%D9%87-%D8%A8%D9%87-%D9%87%D9%85-%D8%AF%D8%B1-yii/ "Persian Version")