I have a form that has only two checkboxes. When both are unchecked the request
is empty and so the submitted form is not treated in the controller.
Any idea, how I can post something in the request for 'unchecked' checkboxes?
[...]
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
}
[...]
I added a hidden-field, that solved the issue.
[...]
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',
]);
}
[...]