Home > Software design >  Symfony Ajax Form - Choice Type Options depend on other unmapped Choice Type Options
Symfony Ajax Form - Choice Type Options depend on other unmapped Choice Type Options

Time:02-15

i try to keep it short.

I want to change the possible choice opotion of my ChoiceType(N.2), depending on another ChoiceType(N.1).

  • My ChoiceType(N.1) is unmapped and has the Option "Yes" or "No"
  • My ChoiceType(N.2) is mapped and filled with categorys out of an database.

The database has the Columns ID(int) | Name(string) | Revenue(boolean)

So if the user chooce the Option Yes, i want all Categorys in the ChoiceType (N.2) with the revenue of 1(true). If the user choose No, i want to display all choice options with the categorys with the revenue of 0 (boolean)

I've done a lot of research but I just can't get it to work. I mainly focus on de documentaion https://symfony.com/doc/current/form/dynamic_form_modification.html, but there both ChoiceTyps are Entitys, not just one. I should almost have it, but I don't know what's missing. Here are the important parts of my code:

EntryForm:

   ->add('choice', ChoiceType::class, [
            'choices'  => [
                'No' => 0,
                'Yes' => 1,
            ],
            'data'=>0,
            'mapped' => false,
        ])

 

 
        $formModifier = function (FormInterface $form, $choice) {
   
           
            $revenue = $choice;
            $user = $this->security->getUser();
            $userId = $user->getId();

            $form->add('category', EntityType::class,[
                'class'=>Category::class,
                'query_builder' => function(CategoryRepository $repository) use($userId,    
                         $revenue) {
                    $qb = $repository->createQueryBuilder('u');
           
                    return $qb
           
                        ->where('u.user=' .$userId, 'u.revenue='.   $revenue );
                }, ]);
           
        };
 
 
       
        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
 
                $data = $event->getData();
                $form = $event->getForm();
                $choice = $form->get('choice')->getData();
 
                $formModifier($event->getForm(),  $choice);
            }
        );
 

 
        $builder->get('choice')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
         
                $choice = $event->getForm()->getData();
     
                $formModifier($event->getForm()->getParent(), $choice);
            }
        );

AJAX

var $choice = $('#entry_choice');
 
    $choice.change(function() {
   
        var $form = $(this).closest('form');
        var data = {};
     
        var choice = $('#entry_choice').val();
         
         data= choice;
           data[$choice] = 1;
           
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
           data : data,
           
            complete: function(html) {
                console.log( data);
                  
              $('#entry_category').replaceWith(
      
        
      $(html.responseText).find('#entry_category'));
     
            }
        });
    });

I think I don't understand the data passed from ajax correctly. I am trying to achieve the following: If the user change the ChoiceType from No to Yes, pass the variable $choice with the value 1 to the form. In the form at the $formModifier it should change the variable $revenue to $choice, so that i can filter with my query_builder through all categorys where revenue is 1. ('u.revenue='. $revenue)

Kind regards Magnus

CodePudding user response:

Instead of data[$choice] = 1; try data[$choice.attr('name')] = 1;

Symfony expects the data to be sent from the front end in a specific format.

If you inspect the source of the generated html form, you will see that format.

  • Related