T
T
test2018-08-07 18:46:57
symfony
test, 2018-08-07 18:46:57

Symfony how to merge - conditions in validation?

How can you do this If you are an entity 2 fields are not valid(@Assert\NotBlank()) then consider it an error, but if one of them is valid then everything is OK

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2018-08-07
@HelmutKampfe

symfony.com/doc/current/reference/constraints/Call...

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Model
{
    /**
     * @var string
     */
    public $foo;

    /**
     * @var string
     */
    public $bar;

    /**
     * @Assert\Callback()
     *
     * @param ExecutionContextInterface $context
     * @param $payload
     */
    public function validateFooBar(ExecutionContextInterface $context, $payload)
    {
        $fooViolations = $context->getValidator()->validate($this->foo, new Assert\NotBlank());
        $barViolations = $context->getValidator()->validate($this->bar, new Assert\NotBlank());

        if ($fooViolations->count() > 0 && $barViolations->count() > 0) {
            $context->buildViolation('foo или bar должны быть заполнены')
                ->addViolation()
            ;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question