Dynamic dropdown in cakephp 2.0 (Selectbox)

Hello Friend, In this post i want to show you how to create dynamic dropdown in cakephp 2.x using ajax auto populating Select boxes, country state city selectbox in cakephp, cake selection box, Dependent dropdown in cakephp.

Database & Tables

First of all open mysql and create one database dropdowns this database contains three tables countries states and cities as below. state table has relation with country table and city table has relation with state table.

   Country State City tabel

// countries tabel

DROP TABLE IF EXISTS `countries`;
CREATE TABLE `countries` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(25) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


// states table
DROP TABLE IF EXISTS `states`;
CREATE TABLE `states` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `countries_id` int(3) NOT NULL,
  `state_name` varchar(35) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


// cities table 
DROP TABLE IF EXISTS `cities`;
CREATE TABLE `cities` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `state_id` int(3) NOT NULL,
  `city_name` varchar(35) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

More Information about cakephp click here.

  1. Controller File (app\Controller\CountriesController.php)
<?php
class CountriesController extends AppController {
	public $helpers = array('Html', 'Form', 'Session');
	public $components = array('RequestHandler');
	
	public function getStates() {
		$states = array();
		if (isset($this->request['data']['id'])) {
			$states = $this->Country->State->find('list', array(
				'fields' => array(
					'id',
					'state_name',
				),
				'conditions' => array(
					'State.countries_id' => $this->request['data']['id']
				)
			));
		}
		header('Content-Type: application/json');
		echo json_encode($states);
		exit();
	}
	//www.techsofttutorials.com
	// free latest programming technology tutorials and demo.
	public function index() {
		$Country = $this->Country->find('list', array(
			'fields' => array(
				'id',
				'country_name',
			),
		));
		$this->set('Country', $Country);
	}

	public function getCities() {
		$cities = array();
		if (isset($this->request['data']['id'])) {
			$cities = $this->Country->State->City->find('list', array(
				'fields' => array(
					'id',
					'city_name',
				),
				'conditions' => array(
					'City.state_id' => $this->request['data']['id']
				)
			));
		}
		header('Content-Type: application/json');
		echo json_encode($cities);
		exit();
	}
}

2) Country Model File(app\Model\Country.php)

<?php
class Country extends Model {

	public $hasMany = array(
			'State'
	);
}
//www.techsofttutorials.com  free latest technology tutorials

3) State Model File (app\Model\State.php)

<?php
class State extends Model {
	public $belongsTo = array(
			'Country'
	);
	public $hasMany = array(
			'City'
	);
}

//www.techsofttutorials.com Free latest technology tutorials

4) Cities Model file (app\Model\City.php)

<?php
class City extends Model {

	public $belongsTo = array(
			'State'
	);
	
}

5) View File (app\View\Countries\index.ctp)

<?php
	echo $this->Html->script('jquery.min');
	echo $this->Form->input('country', array(
		'id' =>'country',
		'options' => $Country,
		'empty' => 'select country',
	));
	echo $this->Html->image('ajax-loader.gif', array('alt' => 'lodding', 'id' => 'loding1'));
	echo $this->Form->input('state', array(
		'id' =>'state',
		//'type' => 'select'
		'options' => '$states',
		'empty' => 'select state',
	));
	echo $this->Html->image('ajax-loader.gif', array('alt' => 'lodding', 'id' => 'loding2'));
	echo $this->Form->input('city', array(
		'id' =>'city',
		//'type' => 'select'
		'empty' => 'select city',
		'options' => '$city',
	));
?>
<script type="text/javascript">
	$(document).ready(function() {
		$("#loding1").hide();
		$("#loding2").hide();
		$("#country").on('change',function() {
			var id = $(this).val();
			$("#loding1").show();
			$("#state").find('option').remove();
			$("#city").find('option').remove();
			if (id) {
				var dataString = 'id='+ id;
				$.ajax({
					type: "POST",
					url: '<?php echo Router::url(array("controller" => "countries", "action" => "getStates")); ?>' ,
					data: dataString,
					cache: false,
					success: function(html) {
						$("#loding1").hide();
						$.each(html, function(key, value) {              
							$('<option>').val('').text('select');
							$('<option>').val(key).text(value).appendTo($("#state"));
						});
					} 
				});
			}
		});

		$("#state").on('change',function() {
			var id = $(this).val();
			$("#loding2").show();
			$("#city").find('option').remove();
			if (id) {
				var dataString = 'id='+ id;
				$.ajax({
					type: "POST",
					url: '<?php echo Router::url(array("controller" => "countries", "action" => "getCities")); ?>',
					data: dataString,
					cache: false,
					success: function(html) {
						$("#loding2").hide();
						$.each(html, function(key, value) {              
							$('<option>').val(key).text(value).appendTo($("#city"));
						});
					} 
				});
			}	
		});
	});
</script>