Validating dynamically loaded choices in Symfony 2

Chris picture Chris · Oct 18, 2012 · Viewed 9.5k times · Source

I have a choice field type named *sub_choice* in my form whose choices will be dynamically loaded through AJAX depending on the selected value of the parent choice field, named *parent_choice*. Loading the choices works perfectly but I'm encountering a problem when validating the value of the sub_choice upon submission. It gives a "This value is not valid" validation error since the submitted value is not in the choices of the sub_choice field when it was built. So is there a way I can properly validate the submitted value of the sub_choice field? Below is the code for building my form. I'm using Symfony 2.1.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('parent_choice', 'entity', array(
                    'label' => 'Parent Choice',
                    'class' => 'Acme\TestBundle\Entity\ParentChoice'
    ));

    $builder->add('sub_choice', 'choice', array(
                    'label' => 'Sub Choice',
                    'choices' => array(),
                    'virtual' => true
    ));
}

Answer

Eugene Leonovich picture Eugene Leonovich · Apr 16, 2014

To do the trick you need to overwrite the sub_choice field before submitting the form:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    ...

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $parentChoice = $event->getData();
        $subChoices = $this->getValidChoicesFor($parentChoice);

        $event->getForm()->add('sub_choice', 'choice', [
            'label'   => 'Sub Choice',
            'choices' => $subChoices,
        ]);
    });
}