Creating Dynamic Select (Drop Down Input) with CakePHP

This Creating Dynamic Select lesson only works with CakePHP 2.x and above

In this tutorial, I will show you how to populate a drop down field according to another drop down selection using CakePHP 2.x. The idea is simple and will require you to have two related tables. What I will be using in this example is country – city relationship where city belongsTo country, and country hasMany city. Make sure of the right relationship or else this will not work.

In the Country View where you want to put your drop down. Add the following code

This will create two dropdown Country and its child City. In order for these select to function, you will have to set each ID attribute

At the bottom of all your codes, include this AJAX script to be able to send data from your view to your controller in client mode.

The get_by_country tells which action in the countriesController will be triggered. As for now we don’t have that custom function just yet.

Next we will create a custom function in our countriesController called get_by_country. The purpose of this function is to set data from view to view that was triggered by the AJAX script.

The last part will be creating the get_by_country.ctp view that will display the data being populated.

Now when you select an item from Country, it will give you the Cities belongs to that country.

Sharing is caring!