Reputation: 117
I've been working on this problem for a few days now with no luck. I'm trying to implement a simple ajax call in CakePHP 2.0 that will populate a select list based on the selection of another select list. In my database I have vehicle makes and vehicle models. The models have a make_id field. When a user selects a make, I want the model select list populated with only models that have a make_id of the one previously selected. When I view the request in Firebug, it's sending back all models regardless of make_id. I found this small tutorial that attempts to explain how to populate a select based off another select, but I'm still having no luck. http://bakery.cakephp.org/articles/Calderoy/2011/01/18/how_to_create_an_observefield_equivalent_in_the_new_jshelper
Here is my JsHelper code, found in my view file:
$this->Js->get('#CarMakeId')->event(
'change',
$this->Js->request(
array('controller' => 'CarModels', 'action' => 'get_model'),
array(
'async' => true,
'update' => '#CarCarModelId',
'dataExpression' => true,
'method' => 'post',
'data' => $this->Js->serializeForm(array('isForm' => true, 'inline' => true))
)
)
);
And here is my controller method:
public function get_model() {
$models = $this->CarModel->find(
'all',
array('conditions',
array('CarModel.make_id' => $this->data['Car']['make_id'])
)
);
$this->set('car_models', $models);
}
Finally, here is my get_model view file:
if($car_models) {
echo "<option value=''>-- Select --</option>\n";
foreach($car_models as $model) {
echo "<option value=".$model['CarModel']['id'].">".$model['CarModel']['name']."</option>\n";
}
}
This is the javascript that is created via JsHelper:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#CarMakeId").bind("change", function (event) {$.ajax({async:true, data:$("#CarMakeId").serialize(), dataType:"html", success:function (data, textStatus) {$("#CarCarModelId").html(data);}, type:"post", url:"\/Dropbox\/CartrackerV3\/CarModels\/get_model"});
return false;});});
//]]>
I have included the RequestHandler helper in my controller. It's also worth noting that I am getting a response from the ajax call. After I choose a make, the first option in models changes from a blank option to the -- Select -- option, which comes from the get_model view file, however it is still listing every model in the database, not just the ones with the correct make_id.
Upvotes: 1
Views: 2205
Reputation: 29121
Per the comment by the OP, the issue was just a syntax issue - the comma in:
array('conditions', array('CarModel.make_id
should be a =>
:
array('conditions' => array('CarModel.make_id
Upvotes: 1