A better and cleaner solution https://symfony.com/doc/3.4/validation/custom_constraint.html
is to write
- a custom constraint (which is basically the error message)
- and its validator (which is like a controller function that does the control
To check that the entity is fine, add to the custom contraint (not the validator)
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
Which allows you to use an instance of that entity instead of just a property value. That make possible to write in the validator:
public function validate($object, Constraint $constraint)
{
#Your logic, for example:
if($value1 = $object->getValue1())
{
if($value2 = $object->getValue2())
{
if($value1 === $value2)
{
# validation passed
return True;
}
else
{
# validation failed
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value1.' !== '.$value2)
->addViolation();
}
The best part is what you need to write in the entity class:
use YourBundle\Validator\Constraints as YourAssert;
/**
* Yourentity
*
* @ORM\Table(name="yourentity")
* @ORM\Entity(repositoryClass="YourBundle\Repository\YourentityRepository")
*
* @YourAssert\YourConstraintClassName # <-- as simple as this
Hope that helps