【发布时间】:2021-07-17 23:14:29
【问题描述】:
我有一个只有两个复选框的表单。当两者都未选中时,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
}
[...]
【问题讨论】:
-
如果它没有进入isValid,那么你可能有错误。当你转储 $form->getErrors() 时,你能说出你得到了什么吗?
-
错误为空。备注:请求也是空的(dump($request->request);)
-
$form->isSubmitted() 怎么样?是真的吗?
-
您应该添加一个提交按钮(这将发送其值而不会产生进一步的后果)或带有一些随机字段的隐藏字段(隐藏类型)。 csrf_protection 也足够了。但是,请检查提交按钮是否在
<form> -
您是否禁用了 csrf 保护?如果不是,则应添加隐藏输入,使请求非空(并提高整体安全性)
标签: forms symfony checkbox toggle is-empty