r3m4k3 r3m4k3 - 2 years ago 66
PHP Question

Symfony3 validate field only when adding object

I have got some problem.
In the enitity I have set validation.
I have there term field, which is required (NotBlank constraint).
It works fine, but when someone is editing the object I want to disable the validation on this field; then it's not required, because someone already uploaded this file. Of course I have only one form, one view and two actions in controller.
How can I deal with such situation?


Answer Source

You can use a Callback for this.

Since validation takes place before flushing, your entity won't have an id, add a constraint that looks like this:

class YourEntity
    // ...
    private $term;

    * @Assert\Callback
    public function validate(ExecutionContextInterface $context)
        if (!$this->getId() && !$this->getTerm()) {
            $context->buildViolation('This field is required!')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download