Symfony2 Validating an optional field

fkoessler picture fkoessler · Oct 30, 2012 · Viewed 7.9k times · Source

In my form, I have a field with required option set to false, this field is optional.

However, I would like to have a notBlank validation on this field when the field is used:

@Assert\NotBlank(
 *     message="The name field can't be blank",
 *     groups={"flow_poemDataCollector_step1"}
 * )

Right now, I can't use the validation constraint NotBlank because it will cause my form validation to fail when the field is unused.

I tried something to add a random value in the field in a onPostBindRequest listener, but it is complex and didn't manage to have it working. I'm not sure that it is the right way to proceed neither.

Here is what I tried: ($form is a Symfony\Component\Form\FormInterface object)

    $form = $event->getForm();
    $formData = $form->getData();
    $formData->setUserName("foo");
    $form = $form->setData($formData);

But then I get an error that I can't call isValid() on an unbound form.

How can I achieve my goal? ie. Validating the field only in some case.

Answer

Charles-Édouard Coste picture Charles-Édouard Coste · Aug 28, 2016

This is an old question, but it seems that now we can do it this way:

@Assert\Optional(
    @Assert\NotBlank(
        message="The name field can't be blank",
        groups={"flow_poemDataCollector_step1"}
    )
)

ref: http://symfony.com/doc/2.7/reference/constraints/Collection.html