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)
                        )
                    )
                );
            })
        ;
    }
}