Sunday, March 1, 2015

Dropdown Cakephp with Chained Selects Plugin for jQuery and Zepto

http://www.appelsiini.net/projects/chained

Basic setup for Chained Selects Plugin 

1. First you must include jQuery and Chained in your code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.chained.min.js"></script>

2. Then lets assume you have the following HTML code:

<select id="mark" name="mark">
  <option value="">--</option>
  <option value="bmw">BMW</option>
  <option value="audi">Audi</option>
</select>
<select id="series" name="series">
  <option value="">--</option>
  <option value="series-3" class="bmw">3 series</option>
  <option value="series-5" class="bmw">5 series</option>
  <option value="series-6" class="bmw">6 series</option>
  <option value="a3" class="audi">A3</option>
  <option value="a4" class="audi">A4</option>
  <option value="a5" class="audi">A5</option>
</select>

3. You can now chain the #series to #mark. There are two different ways to do it. Choose yourself if you prefer more english like or shorter version. I prefer the shorter version.

$("#series").chained("#mark"); /* or $("#series").chainedTo("#mark"); */


Basic setup for Chained Selects Plugin in Cakephp

1. Make find('all') in any function of controller for custome dropdown

$states = array();
$country = $this->Application->Country->find('list');
$states_id = $this->Application->States->find('all');

//Custome dropdown states
foreach ($states_id as $key => $value) {
            $states[$key] = array(
                'name' => $value['State']['name'],
                'value' => $value['State']['id'],
                'class' => $value['State']['id'] //class like Chained format
}

$this->set(compact('country', 'states'));

2. Write Select Cakephp Helper From

echo $this->Form->input('country_id', array('empty'=>'--Select--'));            
echo $this->Form->input('state_id',  array(
     'type' => 'select','empty'=>'--Select--', 'options' => $states)
);

3. Write script on bottom of page
<script>
    $(function () {
      $("#ApplicationCountryId").chained("#ApplicationStateId"); 
   });
</script>