Building Symfony 2 Custom Validator that Uses Multiple Fields

前端 未结 2 1843
野趣味
野趣味 2021-02-04 03:41

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

相关标签:
2条回答
  • 2021-02-04 04:07

    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();
            /* ... */
        }
    }
    
    0 讨论(0)
  • 2021-02-04 04:18

    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 {
    
    }
    
    0 讨论(0)
提交回复
热议问题