Symfony 表单 ChoiceType 忽略了必需的属性

Symfony form ChoiceType is ignoring the required attribute

我在表单上添加了这样的字段

$builder->add('cse',
ChoiceType::class,
array(
    'label' => '',
    'required' => true,
    'translation_domain' => 'messages',
    'choices' => array(
        'I agree' => true
    ),
    'expanded' => true,
    'multiple' => true,
    'data' => null,
    'attr' => array( 'class' => 'form_f' ),
)

)

虽然添加到表单的所有其他字段将 'required' 设置为 'true' 将阻止发送表单,但此字段的必需属性将被忽略(无论如何都会发送表单是否选中)。

我必须使用 Assert 语句来处理吗?如果是 - 仍然:为什么要求不在这里工作?

是的,使用断言。

因为multiple=true打印checkbox。 Html 验证器可以测试 radio,但不能测试 checkbox

始终对所有表单使用 Assert,因为 html 验证器不安全 :)

在我的例子中,我不能使用断言,因为不可能在用户端处理这个(除非你使用 javascript),我在服务器端进行了检查,在 FormEvents::PRE_SUBMIT hook:

$builder->addEventListener(
    FormEvents::PRE_SUBMIT,
    function (FormEvent $event) {
        if ($field->required && !isset($event->getData()[$field->name])) {
            $event->getForm()->addError(new FormError('One option must be chosen on "' . $field->label . '"'));
        }
    });