1

I have two entity dropdowns field in my symfony form. On the front end i change the option list of 2nd drop drown using ajax based on the value of first dropdown selected value. and Upon submitting the form i get the error that,

This value is not valid.

below is the code;

/**
 * @ORM\ManyToOne(targetEntity="State")
 * @ORM\JoinColumn(name="province_id", referencedColumnName="id")
 */
protected $Province;

/**
 * @ORM\ManyToOne(targetEntity="District")
 * @ORM\JoinColumn(name="district_id", referencedColumnName="id")
 */
protected $District;

and in the form,

 ->add('domicileDistrict','entity', [
                'label' => ucwords('District'),
                'class'=>'GeneralBundle\Entity\District',
                'required' => true,
                'mapped' => true,
                'attr' => ['class' => 'form-control'],
                'label_attr' => ['class' => 'control-label'],
            ])
->add('domicileProvince','entity', [
                'label' => ucwords('Province'),
                'class'=>'GeneralBundle\Entity\State',
                'required' => true,
                'attr' => ['class' => 'form-control select2'],
                'label_attr' => ['class' => 'control-label'],
            ])

and on front end,

 $("#profile_from_type_domicileProvince").change(function() {
                var state = $('option:selected', this).val();
                getDistrictByState(state);
            });

            function getDistrictByState(state){
                var dict = {
                    type: "POST",
                    url: "{{ url('ajax_district_by_stateId') }}?id=" + state,
                    success: function(e) {
                       $("#profile_from_type_domicileDistrict option").remove();
                        $.each(e, function(e, p) {
                            $("#profile_from_type_domicileDistrict").append($("<option />", {
                                value: e,
                                text: p
                            }));
                        });
                    } 
                };
                $.ajax(dict);
            }

UPDATE: Add PRE_SUBMIT Event;

After suggestion form @Alsatian, I update my form and add the event as below, but nothing happens on selecting first dropdown.

$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmitData']);

  public function preSubmitData(FormEvent $event){
        $form = $event->getForm();
        $data = $event->getData();

        if (array_key_exists('Province', $data)) {
            $state = $data['Province'];
            $event->getForm()
                ->add('District','entity', [
                    'label' => ucwords('District'),
                    'class'=>'GeneralBundle\Entity\District',
                    'required' => true,
                    'mapped' => true,
                    'query_builder' => function(DistrictRepository $repository) use ($state) {
                        $qb = $repository->createQueryBuilder('d')
                            ->andWhere('d.verified = :verified')
                            ->andWhere('d.active = :active')
                            ->setParameter('verified', true)
                            ->setParameter('active', true);

                        if ($state instanceof State) {
                            $qb = $qb->where('d.state = :state')
                                ->setParameter('state', $state);
                        } elseif (is_numeric($state)) {
                            $qb = $qb->where('d.state = :state')
                                ->setParameter('state', $state);
                        } else {
                            $qb = $qb->where('d.state = 1');
                        }

                        return $qb;
                    },
                    'attr' => ['class' => 'form-control select2'],
                    'label_attr' => ['class' => 'control-label'],
                ]);

        }
    }
2
  • PRE_SUBMIT does nothing on change of first select box as your are asking. when form submitted, It will populate required options to dynamic select box. Do you still get This value is not valid. error on submission? Commented Jul 20, 2016 at 11:19
  • @Jeet yes, i got the error, so what did on pre submit event, i get the selected dropdown value and convert it into the object and set the form field data attribute. now it did not prompts any erorr. Commented Jul 20, 2016 at 12:54

1 Answer 1

1

I had the same problem.

I wrote a bundle here to deal with "extensible" choice types (also entity or document) : https://github.com/Alsatian67/FormBundle/blob/master/Form/Extensions/ExtensibleSubscriber.php

How I do it :

Hooking in the form submission process, we can access to the submitted entity by the PRE_SUBMIT FormEvent. All submitted entity are loaded and are in $event->getData().

Then we have just to take this submitted choices as new 'choices' option for the field.

Caution : Doing it so it will only validate that the entity submitted exist ! If only a part of the entities are possible choices you have to add a constraint to validate them.

You can also set the choices in the PRE_SUBMIT event, depending on the value of the first dropdown (instead of using all submitted entities).

Sign up to request clarification or add additional context in comments.

3 Comments

i have added the event, but on changing province dropdown nohting happens. See the updated questions now.
This event is only fired when you submit your form.
Write some exit(dump('foo')); in your preSubmitData method to know if it is fired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.