Home » Php » php – Symfony 2.5 addViolationAt deprecated, use buildViolation()

php – Symfony 2.5 addViolationAt deprecated, use buildViolation()

Posted by: admin July 12, 2020 Leave a comment


I have been following the cookbook on how to create a class constraint validator and right now I am at the point where I am about to add the violation in the validate() function.

However my IDE notifies me the functions addViolation() and addViolationAt() are deprecated.

Can someone point me in the right direction on how to use the Context\ExecutionContextInterface::buildViolation() function instead?

$this->context is an instance of Symfony\Component\Validator\ExecutionContext

class ProtocolClassValidator extends ConstraintValidator
    public function validate($protocol, Constraint $constraint)
        if ($protocol->getFoo() != $protocol->getBar()) {

When changing the call $this->context->addViolationAt() to simply $this->context->buildViolation(), I get the following Exception:

UndefinedMethodException: Attempted to call method “buildViolation” on
class “Symfony\Component\Validator\ExecutionContext” in
stripped path
line 23. Did you mean to call: “addViolation”?

and line 23 has the following code:

    $builder = $this->context->buildViolation($constraint->message)
How to&Answers:

addViolation and addViolationAt are deprecated from 2.5 but won’t be removed until 3.0 so they are still usable for a good time.

However… taken from the the UPGRADE FROM 2.x to 3.0 log…

The method `addViolationAt()` was removed. You should use `buildViolation()`


$context->addViolationAt('property', 'The value {{ value }} is invalid.', array(
    '{{ value }}' => $invalidValue,


$context->buildViolation('The value {{ value }} is invalid.')
    ->setParameter('{{ value }}', $invalidValue)

With a bit more taken from Context/ExecutionContextInterface

 * Returns a builder for adding a violation with extended information.
 * Call {@link ConstraintViolationBuilderInterface::addViolation()} to
 * add the violation when you're done with the configuration:
 *     $context->buildViolation('Please enter a number between %min% and %max.')
 *         ->setParameter('%min%', 3)
 *         ->setParameter('%max%', 10)
 *         ->setTranslationDomain('number_validation')
 *         ->addViolation();
 * @param string $message    The error message
 * @param array  $parameters The parameters substituted in the error message
 * @return ConstraintViolationBuilderInterface The violation builder
public function buildViolation($message, array $parameters = array());