Yii2 Tips 28 : Dependent Dropdown Without Extension

This tip will show you how to create dependent dropdown without using any extensions.

1. Create table country and table city.

yii2 tips depdrop

yii2 tips depdrop

2. Create models Country and City using gii.

3. Add actionDependentDropdown on your controller (i.e. TestController.php)

4. Add the view file, dependent-dropdown.php inside the view folder, take note to the ‘onchange’ event when the first dropdown is selected :

5. The last step is to add the actionCountryList($id) inside the controller.

6. Your dependent dropdown now has functioned properly. If you select one Country, the city dropdown value corresponds to the country that you’ve chosen.

yii2 tips depdrop

4 thoughts on “Yii2 Tips 28 : Dependent Dropdown Without Extension

  • I have a question, I’ve been having the same issue and none of the answers or research I’ve done has worked.
    Do I really need to create another view the dependent-dropdown view? I have my _form.php and there is where I have everything, do I need to create another view or with my regular _form.php will it work?

    Thank you

  • Any view actually works. You don’t have to create dependent-dropdown.php as your _form.php can be functioned properly. You just need to render the view from controller to _form.php

  • Hey, I’m new to yii2. I’m trying to access the view frontend/web/dependent-dropdown.php after following all the instructions and it’s not showing me the page. It says the object is not found.

    • Did you put the dependent-dropdown.php inside view folder with the same name as the controller? E.g if your controller name is TestController.php then you should put the file inside /views/test folder.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.