1
votes

I have got a simple smyfony2 form with one choices element. When I choose "kerosin" or "diesel" the form won't validate, what is correct. When I won't choose any of the three options and submit the form empty, $form->validate() will return true, but it shouldn't. Any ideas? Using the HTML5 required is not a solution for me.

This is my Form AbstractType:

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

    // Form erzeugen
    $builder->add('treibstoff', 'choice', array(
            'choices' => array(
                    'kerosin' => 'form.quiz1.kerosin',
                    'benzin' => 'form.quiz1.benzin',
                    'diesel' => 'form.quiz1.diesel',
                ),
            'multiple' => false,
            'expanded' => true,
            'label' => ' '
        ))
        ->getForm();
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{

    // Validierung erzeugen
    $collectionConstraint = new Collection(array(
        'treibstoff' => array(
                new Choice(array(
                    'choices' => array('benzin'),
                    'message' => 'form.quiz.falscheantwort',
                    'strict' => true
                )
            )
        )
    ));

    $resolver->setDefaults(array(
        'validation_constraint' => $collectionConstraint
    ));
}

public function getName()
{ 
     ...

Validation works like this:

    if($Request->getMethod() == "POST") {
        $form->bind($Request);
        if($form->isValid()) {
            echo "valid";

Thanks in advance.

Edit:

I changed the setDefaultOptions like suggested and added NotBlank. That worked out for me:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{

    // Validierung erzeugen
    $collectionConstraint = new Collection(array(
        'treibstoff' => array(
            new Choice(array(
                    'choices' => array('benzin'),
                    'message' => 'form.quiz.falscheantwort',
                    'strict' => true,
                )
            ),
            new NotBlank()
        )
    ));

    $resolver->setDefaults(array(
        'validation_constraint' => $collectionConstraint
    ));
}
1

1 Answers

3
votes

You set only valid choice to benzin in setDefaultOptions, but you didn't specify the field as required. Note that required in form field only sets HTML5 validation on:

Also note that setting the required option to true will not result in server-side validation to be applied. In other words, if a user submits a blank value for the field (either with an old browser or web service, for example), it will be accepted as a valid value unless you use Symfony's NotBlank or NotNull validation constraint.

So, you'll have to add also NotBlank constraint to treibstoff field.