我想比较表格SYMFONY4

时间:2019-04-19 21:16:25

标签: php symfony validation constraints symfony4

我有这个表单类型:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('ageMin', NumberType::class),
            ->add('ageMax', NumberType::class,[
'mapped' => false
]);
    }

我的问题,我想在提交以下表格之前验证此表达式:ageMin <= ageMax

我已经尝试过此代码,但无法正常工作

    $resolver->setDefaults([
            'data_class' => User::class,
            'constraints' => [
new Assert\Expression([
                'expression' => 'value["ageMax] >= value["ageMin"]'
            ]),
]
        ]);

如果还有其他解决方案?

3 个答案:

答案 0 :(得分:1)

您可以使用以下任一方法轻松解决此问题

  1. Constraints Expression

  2. Custom Validation Constraint

答案 1 :(得分:0)

您可以使用类约束验证器:

class UserAgeValidator extends ConstraintValidator
{
    public function validate($user, Constraint $constraint)
    {
        if ($user->getAgeMax() >= $user->getAgeMin()) {
            $this->context->buildViolation($constraint->message)
                ->atPath('ageMin')
                ->addViolation();
            $this->context->buildViolation($constraint->message)
                ->atPath('ageMax')
                ->addViolation();
        }
    }
}

参考文档:

https://symfony.com/doc/current/validation/custom_constraint.html#class-constraint-validator

答案 2 :(得分:0)

utf-8