Reputation: 61
How do i deal with dependent combo boxes in the views with the form helper. For example:
Country Select Box (Choosing a country shall filter out the states of the selected country) States Select Box
This should happen with the help of Javascript / Jquery etc. I came across an example for the same with Cake's core AJAX helper but it would be very nice if someone can help with a Javascript example.
Thanks
Upvotes: 2
Views: 8973
Reputation: 1138
In views/ edit.ctp
<script type="text/javascript">
$(document).ready(function (){
$('#country').change(function() {
$('#state').load('/controller/getStates/'+$(this).val());
});
});
</script>
<select id="country" name="country">
<option value="1">Greece</option>
</select>
<span id="state">
<select name="state">
<option value=""></option>
</select>
</span>
and in controller.php
function getStates(int countryID){
$this->set('selectbox',
$this->State->find('list',array('conditions'=>'State.Country_id='.$countryID,
'fields;=>array('description')));
}
and views/getStates.ctp
<select name="state">
<option value=""></option>
<?php
foreach($selectbox as $option)
echo '<option value="'.$option['id'].'">'.$option['description'].'</option>'."\n";
?>
</select>
I hope I don't forget something
Upvotes: 8
Reputation: 1
$states = $this->State->find('list', array(
'conditions' => array('State.country_id' =>$codePassed),
'order'=>array('State.stateName ASC'),
'fields' =>array('id','stateName'),
'recursive' => -1
));
$a='';
$a.= "<select name=\"state\">";
$a.= "<option value=\"\">Select state</option>";
foreach($states as $key=>$value){
$a.="<option value=\"$key\">".$value."</option>";
}
$a.="</select>";
Upvotes: -2
Reputation: 1155
@gong's solution works well. Just remember to add:
$this->layout = 'ajax';
in the controller and ensure there is a clean ajax.ctp in the layouts folder... otherwise all the layout code will be returned in the ajax response as well as just the dropdown code!
Upvotes: 2