FormEventsPRE SUBMIT

此示例是关于根据用户之前使用表单执行的决策来更改表单。

在我的特殊情况下,如果未设置某个复选框,我需要禁用选择框。

所以我们有了 FormBuilder,我们将在 FormEvents::PRE_SUBMIT 事件中设置 EventListener。我们正在使用此事件,因为表单已经使用表单的提交数据进行了设置,但我们仍然可以操作表单。

class ExampleFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $data = $builder->getData();
        $builder
            ->add('choiceField', ChoiceType::class, array(
                'choices' => array(
                    'A' => '1',
                    'B' => '2'
                ),
                'choices_as_values' => true,
            ))
            ->add('hiddenField', HiddenType::class, array(
                'required' => false,
                'label' => ''
            ))
            ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {

                // get the form from the event
                $form = $event->getForm();

                // get the form element and its options
                $config = $form->get('choiceField')->getConfig();
                $options = $config->getOptions();

                // get the form data, that got submitted by the user with this request / event
                $data = $event->getData();

                // overwrite the choice field with the options, you want to set
                // in this case, we'll disable the field, if the hidden field isn't set
                $form->add(
                    'choiceField',
                    $config->getType()->getName(),
                    array_replace(
                        $options, array(
                            'disabled' => ($data['hiddenField'] == 0 ? true : false)
                        )
                    )
                );
            })
        ;
    }
}