所以我有这个Symfony Form字段:

$builder
    ->add('field1', CheckboxType::class, [
        'required' => false,
    ])
    ->add('field2', NumberType::class, [
        'disabled' => !$entite->getField1(),
        'required' => $entite->getField1(),
    ]);

构建表单时,将根据实体field1值设置field2属性 .

然后,在表单中,field2 HTML属性使用javascript动态更改:如果field1值更改,则相应地添加或删除“disabled”/“required”属性 .

问题是,如果在构建表单时禁用field2,然后在使用js启用id时,如果我们提交表单,则在PHP中仍然禁用field2 .

所以我也通过在FormType中添加这个来更改php中的属性:

...
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmit']);
....
public function preSubmit(FormEvent $event)
{
    $data = $event->getData(); // here $data['field2'] has the correct value
    $form = $event->getForm(); // here $form->get('field2') value is null and disabled is true

    // trying to remove the field
    $form->remove('field2');

    // And then re-add it with new attributes
    $form
        ->add('field2', NumberType::class, [
            'data'     => $data['field2'],
            'disabled' => !$data['field1'],
            'required' => $data['field1'],
        ]);
}

那么提交后更改属性字段是否有一种更好的方法(不删除和添加具有新属性的字段)?

Edit

所以这一直有效,直到我为field2设置了一个不正确的值类型 . field2是一个NumberType,我设置一个alpha值(如'azerty'),而不是返回带有fild错误消息的formview,我得到一个Symfony错误:

A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead.

我如何防止这种情况并获取字段错误消息 .

谢谢 .