如果同级(复选框)字段包含“false",则跳过验证 [英] Skip validation if sibling (checkbox) field contains 'false'

查看:22
本文介绍了如果同级(复选框)字段包含“false",则跳过验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含复选框和值字段"的表单.值字段可以是任何内容,文本框、复合字段、集合 - 任何内容.

I have a form containing a checkbox and a "value field". The value field could be anything, a text box, a compound field, a collection - anything.

表单可能如下所示,例如:

The form could look like this, for example:

field_1_label    enabled    [x]
                 value      [________]

field_2_label    enabled    [x]
                 value      sub_field_1    [________]
                            sub_field_2    [________]

field_3_label    enabled    [x]
                 value      [________]

当启用"字段包含 true 时,一切正常.当启用"字段包含 false 时,我想禁用对值字段及其子字段的验证.

When the "enabled" field contains true, everything works fine already. When the "enabled" field contains false, I would like to disable validation on the value field and it's child fields.

因此,当取消选中启用"时,我将有效地忽略该字段.我仍然会在表单中显示它,但我不会存储数据,我当然不希望它被验证.

So when "enabled" is un-checked, I will effectively ignore the field. I will still display it in the form, but I won't store the data and I certainly don't want it validated.

有人对我如何做到这一点有建议吗?具体来说,我在让验证系统忽略值字段任何潜在的子字段时遇到问题.

Does anybody have suggestions for how I might do this? Specifically, I'm having problems getting the validation system to ignore the value field and any potential child fields.

推荐答案

在 Symfony 2.3 中,您可以在 validation_groups 中使用 false 来不应用任何约束:

In Symfony 2.3 you can use false in validation_groups to have no constraints applied:

http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data

例如,在包含复选框和值字段的字段上:

So for example, on the field containing the checkbox and value field:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
        ->setDefaults([
            'validation_groups' => function(FormInterface $form) {
                // If the form is disabled, don't use any constraints
                if ($form->get('enabled_checkbox')->getData() == false) {
                    return false;
                }

                // Otherwise, use the default validation group
                return 'Default';
            }
        ]);
}

这篇关于如果同级(复选框)字段包含“false",则跳过验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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