简体   繁体   中英

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?

Thanks

You can achieve this behaviour by validation groups: http://symfony.com/doc/current/book/validation.html#validation-groups

The definition would be:

/**
 * @Assert\NotBlank(groups={"creation"})
 */
private $terms;

And for the validation you do:

$errors = $validator->validate($someVar, null, array('creation'));

when creating and

$errors = $validator->validate($someVar, null, array('edit'));

when editing.

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!')
                ->atPath('term')
                ->addViolation();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM