Reputation: 4118
I haven't found any comprehensive answer at the moment .. I would like to learn how to change a select option based on the choices of another select. eg. Category One-to-Many SubCategory
I select an option from the Category and SubCategory select content changes. Could you give me a hand?
Upvotes: 4
Views: 5036
Reputation: 4118
in the end I decided to use this method: javascript:
$('select[name*="[category][category]"]').prop('selected', true).change(function(){
var Id = $(this).val();
var url = Routing.generate('route_to_retrieve_subcategory');
$.post(url,
{ 'idCat': Id
}, function(results){
var sub = $('select[name*="[category][category]"]').parent().find('select[name*="[subCategory][]"]');
sub.empty();
$.each(results , function(key, value) {
sub
.append($("<option></option>")
.attr("value",value.id)
.text(value.subCategory));
});
});
});
controller:
public function getSubcategoryAction(Request $request)
{
$Id = $request->get('idCat');
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyBusinessBundle:SubCategories')->findSubCategories($Id);
$output = array();
foreach ($entities as $member) {
$output[] = array(
'id' => $member->getId(),
'subCategory' => $member->getSubCategory(),
);
}
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
route:
route_to_retrieve_subcategory:
pattern: /route_to_retrieve_subcategory
defaults: { _controller: "MyBusinessBundle:ajax:getSubcategory" }
options:
expose: true
I prefer not to pass parameters through the course, I feel that it does not make sense!
A big thank you to shrujan shetty for the inspiration.
Upvotes: 2
Reputation: 2392
First you need to use the routing url to pass the control to the action using jquery eg
$('# category id').change(function(){
var Id = $('#category id').val();
var url = Routing.generate('route_to_retrieve_subcategory', { 'Id': Id });
$.post(url,
{ 'Id': Id
},function(data){
$('#subcategoryId').html(data);
},"text");
}
});
In controller
/**
* @Route("subcategory/{Id}",name="route_to_retrieve_subcategory" )
* @Template()
*/
public function getSubcategoryAction($Id)
{
//code
return new Response($subcategoryList, 200);
}
Note: the route must be listed in routing.yml file
route_to_retrieve_subcategory:
pattern: /route_to_retrieve_subcategory/{Id}
defaults: {_controller: YourBundle:YourController:getSubcategory}
options:
expose: true
Upvotes: 3