doubi8512 2012-10-29 14:45 采纳率: 0%
浏览 38
已采纳

Symfony2根据提交的数据形成验证组

I have some complex form, with several subforms, and I want to be able to validate each subform separately depending on radio button choosen in main form. I wanted to achieve this with validation groups.

Note: I have no data_class model, I work with arrays.

Here is my form simplified:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('xxx', 'text', array(
                'constraints' => array(
                    new Constraints\NotBlank(),
                ),
                'validation_groups' => array(
                    'xxx',
                )
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => function(FormInterface $form) {
                return array('xxx');
            },
        ));
    }
}

The problem is that validation for this field is not triggered.

When this works, I can easily change setDefaultOptions to validate desired group depending on submitted data:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $data = $form->getData();

            return array($data['type']);
        },
    ));
}

Any idea?

  • 写回答

1条回答 默认 最新

  • douao7937 2012-11-02 17:28
    关注

    You have to pass the validation group name to the constraint, not in the form itself. By assigning group name to a form you specify which constraints to use in validation.

    Replace

    $builder->add('xxx', 'text', array(
            'constraints' => array(
                new Constraints\NotBlank(),
            ),
            'validation_groups' => array(
                'xxx',
            )
        ))
    ;
    

    With

    $builder->add('xxx', 'text', array(
            'constraints' => array(
                new Constraints\NotBlank(array(
                    'groups' => 'xxx'
                )),
            ),
        ))
    ;
    

    By default, constraints have the 'Default' (capitalized) group and forms use this group to validate if none specified. If you want the other constraints with no explicit group to validate, along with specified group pass the 'Default' one.

    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $data = $form->getData();
    
            return array($data['type'], 'Default');
        },
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?