Search code examples
phpvalidationsymfony-2.5choicefield

Validate choice list in Symfony2


I have a choice list where user can choose one value, but there I even set an empty value if the user doesn't select anything.

The form does not have model, to use @Assert annotation with it, and the choice field is optional, so in some case it will be hidden and need to be validated only if showed to user.

How I can validate this field? When I set it to required in my form type it didn't help (If I am right required equal to true by defaut). Where is my problem?


Solution

  • You need to add the NotBlank validator to your field.

    You can add a validator directly to your field, like this:

    $this->createFormBuilder()
        ->add('exampleField', 'choice', array(
                'label' => 'Label',
                'constraints' => array(
                    new NotBlank(),
                ),
            ))
    [...]