Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Chain Selection in Cakephp
<?php
App::uses('AppController', 'Controller');
class CountriesController extends AppController {
public $helpers = array('Js');
public $components = array('RequestHandler');
public function select() {
$countries = $this->Country->find('list');
$states = array();
foreach ($countries as $country_id => $name) {
$states = $this->Country->State->findByCountryId($country_id);
break;
}
$this->set(compact('countries', 'states'));
}
public function states_list() {
$this->request->onlyAllow('ajax');
$id = $this->request->query('id');
if (!$id) {
throw new NotFoundException();
}
$states = $this->Country->State->find('list', array(
'conditions' => array('country_id' => $id)
));
$this->set(compact('states'));
}
}
// select.ctp
<?php echo $this->Form->create('Country');?>
<?php echo $this->Html->script('states_ajax'); ?>
<fieldset>
<legend><?php echo __('Countries and States');?></legend>
<?php
$url = $this->Html->url(array('controller' => 'countries', 'action' => 'states_list', 'ext' => 'json'));
$empty = count($states) > 0 ? __('Please Select') : array('0' => __('No States Available'));
echo $this->Form->input('country_id', array('id' => 'countries', 'rel' => $url, 'empty' => 'Choose Country'));
echo $this->Form->input('state_id', array('id' => 'states', 'empty' => $empty));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
// Ajax Code
$(document).ready(function(){
$("#states").attr("disabled","disabled");
$("#countries").change(function(){
$("#states").attr("disabled","disabled");
$("#states").html("<option>Please wait...</option>");
var id = $("#countries option:selected").attr('value');
$.get("/countries/states_list", {id:id}, function(data){
$("#states").removeAttr("disabled");
$("#states").html(data);
});
});
});
@chinel

This comment has been minimized.

Copy link

@chinel chinel commented Mar 3, 2015

please where is the states_ajax file in the $this->Html->script();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.