I\'m building a custom validator that needs to validate the value from TWO form fields in the db in order to get this constraint to pass.
My question is this: the Contra
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:
<?php
namespace 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 {
}