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:

@AssertNotBlank(
 *     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 SymfonyComponentFormFormInterface 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.


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.


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

@AssertOptional(
    @AssertNotBlank(
        message="The name field can't be blank",
        groups={"flow_poemDataCollector_step1"}
    )
)

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


Hmm. I had to reread your question several times because something in it is not logically valid.

If you want the field to be not required then using the NotBlank constraint makes no sense. How can a field be not required and required at the same time?

If all you want is that if something is entered in that field doesn't consist of just spaces, then you don't need the NotBlank constraint at all because Symfony trims the user input by default, so it will end up as if nothing has been entered at all.

链接地址: http://www.djcxy.com/p/57884.html

上一篇: 来自XML的Symfony2验证组件

下一篇: Symfony2验证可选字段