Creating Dynamic Select (Drop Down Input) with CakePHP 2.x tutorial


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

echo $this->Form->input('country_id',array(

    'id' => 'country_id',

    'empty' =>''));

echo $this->Form->input('city_id',array(

    'id' => 'city_id',

    'empty' =>''));

This will create two drop down 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.

<?php

//AJAX for Dynamic Drop down

$this->Js->get('#country_id')->event('change',

    $this->Js->request(array(

        'controller'=>'countries',

        'action' =>'get_by_country',

    ), array(

        'update' =>'#city_id',

        'async' => true,

        'method' => 'Post',

        'dataExpression'=>true,

        'data'=> $this->Js->serializeForm(array(

                'isForm' => true,

                'inline' => true

            ))

    ))

);

// END AJAX

?>


The get_by_country tells which action in the countriesController will be trigger. 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.

public function get_by_country($id=null) {

    $country_id = $this->request->data['Country']['country_id'];

    $this->loadModel("City");

    $subcategories = $this->City->find('list', array(

        'conditions' => array('City.country_id' => $country_id),

        'fields' => 'description',

        'recursive' => -1

    ));

    $this->set('cities',$subcategories);

    $this->layout = 'ajax';

}


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

<option><?php ?></option>

<?php foreach ($cities as $key => $value): ?>

    <option value="<?php echo $key; ?>"><?php echo $value; ?></option>

<?php endforeach; ?>


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

Labels: , ,