french_dev
french_dev

Reputation: 2177

Symfony2.6: make a dynamic ajax form to populate dropdownlist dynamically

I work on a symfony dynamic form, with Ajax. I try to populate dropdownlist dynamically, i-e I want to display results in the second select the results form the firts. And the same for my third select. Indeed, the first dropdown allow users to choose a parc, when they choose a parc, the second select is populated with the results of Ensembles.php belong to the parc, then users can choose in the third dropdown a batiments belong to Ensembles.php. This an example

This form is displayed when I want to add a Zonestechnique. Here are the relation between my entities:

Parcsimmobilier.php <= ManyToOne Ensembles.php <= ManyToOne Batiments.php <= ManyToOne Zonestechnique.php

this is my form ZonestechniqueType.php :

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\ParcsimmobilierRepository;
use Doctrine\ORM\EnsemblesRepository;
use Doctrine\ORM\BatimentsRepository;


class ZonestechniqueType extends AbstractType
{
    /* @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('parcsimmobilier', 'entity', array(
                                    'mapped' => false,
                                    'class'    => 'MySpaceDatabaseBundle:Parcsimmobilier',
                                    'property' => 'nom',
                                    'empty_value' => '-- choose a parc parc --',
                                    'label'    => 'choose a parc immobilier : ',
                                    'multiple' => false,
                                    ))
            ->add('ensembles', 'entity', array(
                                    'mapped' => false,
                                    'multiple' => false,
                                    'class'    => 'MySpaceDatabaseBundle:Ensembles',
                                    'property' => 'nom',
                                    'empty_value' => '-- choose an ensemble --',
                                    'label'    => 'choose an ensemble : ',
                                    ))
            ->add('batiments','entity', array(
                                    'class'    => 'MySpaceDatabaseBundle:Batiments',
                                    'property' => 'nom',
                                    'empty_value' => '-- choose a batiment --',
                                    'label'    => 'choose a batiment : ',
                                    ))
            ->add('categorieszonestechnique')
            ->add('nom')
            ->add('localisation')
            ->add('commentaire')
            ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MySpace\DatabaseBundle\Entity\Zonestechnique'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'mySpace_databasebundle_zonestechnique';
    }
}

I created two methods in my controller. One to display/add a Zonestechnique, and another to populate my dropdown list with Ajax. For now I try with the first two select, i-e I choose a parc, and then the second dropdownlist is populated with the name of all ensembles belonging to the parc I chose.

Here's my controller method:

public function formZonesAction() {

        $request = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();

        if($request->isXmlHttpRequest()) {
            $id = '';
            $id = $request->get('id');

                if ($id != '') {

                    $ensembles = $em->getRepository('MySpaceDatabaseBundle:Ensembles')
                                    ->getEnsemblesByParcsimmobilierQueryBuilder($id);

                    $tabEnsembles = array();
                    $i = 0;

                        foreach($ensembles as $ensemble) {

                            $tabEnsembles[$i]['id'] = $ensemble->getId();
                            $tabEnsembles[$i]['nom'] = $ensemble->getNom();
                            $i++;
                        }

                    $response = new Response();

                    $data = json_encode($tabEnsembles); // formater le résultat de la requête en json

                    $response->headers->set('Content-Type', 'application/json');
                    $response->setContent($data);

                    return $response;
                }

        } else {

            return new Response('no ajax');
        }
    }

/**
     *
     * @Route("/gestionzonestechniquesconformites/addform", name="formZones")
     * @Method("GET")
     */
    public function addZonesConformitesAction() {

        $em=$this->getDoctrine()->getManager();
        $zones = $em->getRepository('MySpaceDatabaseBundle:Zonestechnique');

        $zones = new Zonestechnique;
        $form=$this->createForm(new ZonestechniqueType(), $zones);
        $request = $this->getRequest();

            if($request->isMethod('POST') | $form->isValid()) {

                $form->bind($request);
                $zoneConformite = $form->getData();

                $em->persist($zones);
                $em->flush();

                return $this->redirect($this->generateUrl('indexRechercheZones'));
            }

            else {
                    return $this->render('MySpaceGestionEquipementsTechniquesBundle:ZonesTechnique:addZonesTechniqueConformites.html.twig', array('form' => $form->createView(), 'zone' => $zones ));
                }
    }

This the repository for EnsemblesRepository.php :

class EnsemblesRepository extends EntityRepository
{
    public function getEnsemblesByParcsimmobilierQueryBuilder($id)
    {
        return $this
          ->createQueryBuilder('e')
          ->where('e.parcsimmobilier = :parcsimmobilier')
        ->setParameter('id', $id);
        ;
    }
}

You can find this request in my controller for the Ajax method.

I have no error when I display the form/page, but my Ajax request does not work. This is my routing file:

addZonesConformites:
    path:     /gestionzonestechniquesconformites/add
    defaults: { _controller: MySpaceGestionEquipementsTechniquesBundle:GestionZonesTechniques:addZonesConformites }
    requirements:
    methods: GET

# Ajax
formZones:
    pattern:  /gestionzonestechniquesconformites/addform
    defaults: { _controller: MySpaceGestionEquipementsTechniquesBundle:GestionZonesTechniques:formZones }
    requirements:
    methods: GET

addZonesConformites_process:
    path:     /gestionzonestechniquesconformites/add/process
    defaults: { _controller: MySpaceGestionEquipementsTechniquesBundle:GestionZonesTechniques:addZonesConformites }
    requirements:
    methods: POST

As you can see I have 3 routes, one to display the form, one to populate with Ajax the dropdown and the last to validate the form.

Of course in my twig I made this form:

 <form action="{{ path('addZonesConformites_process') }}" method="POST">
          <div class="row">
            <div class="col-md-6">
              <div>
                {{ form_errors(form) }}
              </div>
              <div>
                {{ form_label(form.parcsimmobilier, "choisir un parc", {'label_attr': {'class': 'control-label'}}) }}
                {{ form_errors(form.parcsimmobilier) }}
                {{ form_widget(form.parcsimmobilier, {'attr': {'class': 'form-control', 'id': 'parcsimmobilier',   'onChange':'populateEnsembles();'}}) }}
              </div>
              <div>
                {{ form_label(form.ensembles, "choisir un ensemble:", {'label_attr': {'class': 'control-label'}}) }}
                {{ form_errors(form.ensembles) }}
                {{ form_widget(form.ensembles, {'attr': {'class': 'form-control', 'id': 'ensembles'}}) }}
              </div>
              <div>
                {{ form_label(form.batiments, "Appartenant au bâtiment:", {'label_attr': {'class': 'control-label'}}) }}
                {{ form_errors(form.batiments) }}
                {{ form_widget(form.batiments, {'attr': {'class': 'form-control'}}) }}
              </div>
<div class="row">
            <div class="clo-md-4"></div>
              <input onclick="clear_form_elements(this.form)" type="reset" value="Vider les champs" class="btn btn-xs btn-default"/>
            </div>
            <br>
            <div class="clo-md-4"></div>
              <input type="submit" value="add" class="btn btn-small btn-success"/>
            </div>
          </div>
        </form>

with this script at the end:

 <script type="text/javascript">
      function populateEnsembles(){
        var id_select = $('#mySpace_databasebundle_zonestechnique_parcsimmobilier').val();
          $.ajax({
            url: "{{ path('addZonesConformites') }}",
            type: 'GET',
            data: {'id': id_select},
            dataType: 'json',
            success: function(json){
              $('#mySpace_databasebundle_zonestechnique_ensembles').html('');
              $.each(json, function(index, value) {
           $('#mySpace_databasebundle_zonestechnique_ensembles').append('<option value="'+ value.id +'">'+ value.nom +'</option>');
              });
            }
          });
      }
    </script>

It's the first time I use Ajax. So I really don't know if it's the right methods, but for now nothing matches and display me what I am trying to make with this dynamic form.

Someone could help me?

This is a screen shot: enter image description here

as you can see, I choose a parc, the ajax request works (symfony toolbar green number at the bottom). And when I proceed a debug in my browser, in the network tab, my ajax request works and returns me the good id of the parc I choose. But it's not populated the second dropdownlist for ensembles. In the second select for ensemble, I have all the ensembles of my database. Thank you in advance.

Upvotes: 2

Views: 2738

Answers (1)

french_dev
french_dev

Reputation: 2177

I found the solution, It was a rookie mistake in fact.

I have to choose the url path of my ajax route and not of my form route. That's why I have no code errors in my console when I debug the application. So this is the line I change in the ajax script: url: "{{ path('addZonesConformites') }}" to url: "{{ path('formRoute') }}"

Upvotes: 2

Related Questions