mlwacosmos
mlwacosmos

Reputation: 4541

Assertions with conditions

I would like to know if it is possible to use asser annotation with conditions.

Using symfony2, in my entity class, on one property I would like to put :

 * @Assert\NotBlank()

if another property has 7 as a value.

Is that possible ?

Upvotes: 0

Views: 530

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

As I mentioned in the comment, you can utilize Callback Constraint

It could look like this:

class YourEntity
{
    /**
     * @Assert\Callback
     */
    public function validate(ExecutionContextInterface $context, $payload)
    {
        if(($this->firstAttr == 7) && empty($this->secondAttr)) {
            $context->buildViolation('Second can\'t be empty when first is 7!')
                ->atPath('secondAttr')
                ->addViolation();
        }
    }
}

You can also make an external callback validator which may be even more suitable since it won't make any mess in you model code (entities).

Upvotes: 1

Related Questions