Building Symfony 2 Custom Validator that Uses Multiple Fields Building Symfony 2 Custom Validator that Uses Multiple Fields symfony symfony

Building Symfony 2 Custom Validator that Uses Multiple Fields


Any custom validator that extends ConstraintValidator has access to the $context property. $context is an instance of ExecutionContext that gives you access to submitted data:

Example:

<?phpnamespace My\Bundle\MyBundle\Validator\Constraints;use Symfony\Component\Validator\Constraint;use Symfony\Component\Validator\ConstraintValidator;class AppointorRoleValidator extends ConstraintValidator{    public function validate($value, Constraint $constraint)    {        $values = $this->context->getRoot()->getData();        /* ... */    }}


You need to use CLASS_CONSTRAINT as described in the cookbooks. You then get passed the whole class and can use any property of this class. In your example above, this would mean that instead of the $value beeing one string/integer, it would be the whole object you want to validate.

The only thing you need to change is getTargets() functions, which has to return self::CLASS_CONSTRAINT.

Also make sure that you define your validator on class level, not on property level. If you use annotations this means that the validator must be described above the class defnition, not above one specific attribute definition:

/**  * @MyValidator\SomeValidator  */class MyClass {}