phpformssymfonyvalidationsymfony2

Symfony2 Validating an optional field


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.


Solution

  • The best way I can see to achieve this is to use a Callback validator on your entity. As this callback is defined in your entity, it has access to all properties. Through the ExecutionContext you can then set violations as needed.