Symfony -форма не обрабатывается, если флажки не отмечены (= запрос пуст) - PullRequest
0 голосов
/ 07 августа 2020

У меня есть форма, в которой всего два флажка. Когда оба флажка не отмечены, поле request пусто, поэтому отправленная форма не обрабатывается в контроллере. * MyChoiceFormType

    [...]

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
            ->add('voucher_buy', CheckboxType::class, [
                'label' => 'buy voucher',
                'data'  => false,               // un-checked as default
                'label_attr' => [
                    'class' => 'switch-custom'  // Bootstrap-toggle (=switch-button)
                ],
            ])
            ->add('voucher_use', CheckboxType::class, [
                'label' => 'use voucher',
                'data'  => false,               // un-checked as default
                'label_attr' => [
                    'class' => 'switch-custom'  // Bootstrap-toggle (=switch-button)
                ],
            ])
        ;
    }

    [...]

контроллер

    [...]

    // generate the FORM
    $form = $this->createForm(MyChoiceFormType::class);


    // handle the submitted FORM
    $form->handleRequest($request);

    if ( $form->isSubmitted() && $form->isValid() ) {
        dd($form->getData());   // <-- not getting here, when both checkboxes are unchecked

        // form shall be treated here and then
        // redirect to another page
    }

    [...]

1 Ответ

0 голосов
/ 07 августа 2020

Dirty Hack

Я добавил скрытое поле, которое решило проблему.

MyChoiceFormType

    [...]

    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
            ->add('voucher_buy', CheckboxType::class, [
                'label' => 'buy voucher',
                'data'  => false,               // un-checked as default
                'label_attr' => [
                    'class' => 'switch-custom'  // Bootstrap-toggle (=switch-button)
                ],
            ])
            ->add('voucher_use', CheckboxType::class, [
                'label' => 'use voucher',
                'data'  => false,               // un-checked as default
                'label_attr' => [
                    'class' => 'switch-custom'  // Bootstrap-toggle (=switch-button)
                ],
            ])
        ;

        // as the from post will be empty, if both checkboxes are unchecked
        // this dummy-field only ensures that at least something is in the
        // posted form
        $builder->add('dummy', HiddenType::class, [
            'data' => 'only_dummy_data',
        ]);
    }

    [...]
...