Choosing Symfony2 ajax

I have not found a complete answer at the moment. I would like to learn how to change a selection parameter based on a selection of another choice. eg. One-to-Many Subcategory

I choose an option from a category and a subcategory to select content. Could you give me a hand?

+4
source share
2 answers

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 this makes no sense!

Many thanks to Shryuzhan Shetti for the inspiration.

+2
source

First you need to use a routing url to push the control into action using jquery e.g.

  $('# 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 the 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 specified in the routing.yml file

 route_to_retrieve_subcategory: pattern: /route_to_retrieve_subcategory/{Id} defaults: {_controller: YourBundle:YourController:getSubcategory} options: expose: true 
+3
source

All Articles