6

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      [________]

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.

4

2 回答 2

9

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

https://symfony.com/doc/current/form/button_based_validation.html

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

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';
            }
        ]);
}
于 2013-06-14T11:57:09.403 回答
2

如果父复选框设置为 false,则只需在验证之前删除子字段。

在食谱文章如何使用表单事件动态修改表单中阅读更多内容。

订阅表单事件 FormEvents::POST_SET_DATA并删除订阅者中的字段。

事件订阅者添加到 Fom 类部分涵盖了这个主题。


您还可以为您的表单引入不同的验证组

如果父复选框设置为 false,只需应用另一个验证组(不包含子字段)。

于 2013-06-14T08:49:33.587 回答