How to make dynamic dependent dorpdown lists in Symfony using Ajax

I tried to make depend dropdown lists in Symfony using Ajax call, when I enter in the specified URL it shows the result I want (array of elements) see the picture url

The result is correct but nothing is showing in the dropdown list, what I’m doing wrong ?
here it is the Form:

 <form method="GET" class="search-jobs-form" id="form" 
          <div class="row mb-5">
            <div class="col-12 col-sm-6 col-md-6 col-lg-3 mb-4 
              <select class="selectpicker dynamic" data-dependent="element" name="category" id="category" data-style="btn-white btn-lg" data-width="100%" data-live-search="true" title="Séléctionner une catégorie">
                {% for category in categories %}     
                {% endfor %}

            <div class="col-12 col-sm-6 col-md-6 col-lg-3 mb-4 mb-lg-0">
              <select class="selectpicker" name="element" id="element" 
              data-style="btn-white btn-lg" data-width="100%"
             <option value="">Select Element</option>

The controller function:

namespace AppController;
use SymfonyComponentRoutingAnnotationRoute;
use AppEntityElement;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationJsonResponse;

     class ListController extends AbstractController

      * @Route("/site/list", name="site.list", methods={"GET","POST"})
   public function getChild(Request $request)

   $slct = $request->query->get('select');

   $val = $request->query->get('value');

   $dpnt =$request->query->get('dependent');

   $em = $this->getDoctrine()->getManager();
   $q= $em->createQuery(
             "SELECT ce
             FROM AppEntityCategoryElements ce WHERE ce.category=:val"
        $q->setParameter('val', $val);

              foreach($data as $row)
               $output[] = $row->$dpnt;

             return new JsonResponse($output);


And the Ajax call in Twig file:

 $(document).ready(function() {
  $('#category').change(function() {
    if ($(this).val() != '') {
        var select = $(this).attr("id");
        var value = $(this).val();
        var dependent = $(this).data('dependent');
        var _token = $('input[name="_token"]').val();
            url: 'site/list',
            method: "GET",
            data: { select: select, value: value, _token: _token, dependent: dependent },
            success: function(data) {
                var htmlOptions = [];
       if( data.length ){
          for( item in data ) {
              html = '<option value="' + data[item] + '">' + data[item] + '</option>';
          htmlOptions[htmlOptions.length] = html;

           $("#element").empty().append( htmlOptions.join('') );



Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *