Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating dynamically loaded choices in Symfony 2

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
    ));
}
like image 543
Chris Avatar asked Oct 18 '12 03:10

Chris


2 Answers

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,
        ]);
    });
}
like image 57
Eugene Leonovich Avatar answered Oct 11 '22 03:10

Eugene Leonovich


this accept any value

 $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
    $data = $event->getData();
    if(is_array($data['tags']))$data=array_flip($data['tags']);
    else $data = array();
    $event->getForm()->add('tags', 'tag', [
        'label'   => 'Sub Choice',
        'choices' => $data,
        'mapped'=>false,
        'required'=>false,
        'multiple'=>true,
    ]);
});
like image 33
Developer Avatar answered Oct 11 '22 03:10

Developer