Pass custom parameters to custom ValidationConstraint in Symfony2

后端 未结 5 1047
梦谈多话
梦谈多话 2021-02-04 02:25

I\'m creating a form in Symfony2. The form only contains one book field which allows the user to choose between a list of Books entities. I need to c

5条回答
  •  梦毁少年i
    2021-02-04 03:25

    Accepted answer did not work for me using Symfony Framework version 2.1. This is how I solved it.

    class CustomConstraint extends Constraint
    {
        public $dependency;
        public $message = 'The error message.';
    }
    
    class CustomConstraintValidator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            if (!$constraint->dependency->allows($value)) {
                $this->context->addViolation($constraint->message);
            }
        }
    }
    
    class CustomFormType extends AbstractType
    {
        private $dependency;
    
        public function __construct(Dependency $dependency)
        {
            $this->dependency = $dependency;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('field', 'type', array(
                    'constraints' => array(
                        new CustomConstraint(array('dependency' => $this->dependency))
                    )
            ));
        }
    } 
    

提交回复
热议问题