在特定验证组的映射=假字段上添加验证约束 [英] Add validation constraints on mapped = false fields for a specific validation group

查看:57
本文介绍了在特定验证组的映射=假字段上添加验证约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在Form类中为特定的验证组添加其他验证约束.我该怎么办?

I'd like to be able to add in a Form class additional validation constraints for a specific validation group. How could I do that ?

从Symfony 2.1开始,在构建表单时添加验证如下所示:

Since Symfony 2.1, adding a validation while building the form looks like this :

use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\NotBlank;

$builder
    ->add('firstName', 'text', array(
        'constraints' => new MinLength(3),
    ))
    ->add('lastName', 'text', array(
        'constraints' => array(
            new NotBlank(),
            new MinLength(3),
        ),
    ))
;

资源

是否可以将它们分配给验证约束?

Is there a way to assign them to a validation constraint ?

就我而言,我有验证组取决于提交的数据

提前感谢您的建议

推荐答案

好的,实际上解决方案很简单.

OK, well the solution was pretty straighforward actually.

Constraint 类中,我注意到了暴露的$ groups属性和addImplicitGroupName(string $ group)方法.

Looking at the Constraint class, I noticed the exposed $groups property and addImplicitGroupName(string $group) method.

知道这一点后,您将了解所有信息:

When you know that, you know all about it:

$cv1 = new NotBlank();
$cv1->groups = array('myGroup');
$cv2 = new NotNull();
$cv2->groups = array('myGroup');
$myCnstrs = array(
    'constraints' => array(
         $cv1,
         $cv2,
     )
);

$myOtherOptions = array(
     ...
);

$builder->add('myField', null, array_merge($myCnstrs,$myOtherOptions));

对不起,如果我在发帖后立即提问并回答该问题,就会被滥用

Sorry if I abused by posting a question and replying to it right after...

这篇关于在特定验证组的映射=假字段上添加验证约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆