获取symfony中复选框的值 [英] get value of checkbox in symfony
问题描述
我想获取复选框的值(选中与否),但复选框未添加到表单类型中.这是一个例子
I want to get the value of checkbox (checked or not), but the checkedbox not added to the form type. this is an example
<input type="checkbox" class="checkbox" id="smsflash">
请问是否有可能获取控制器中复选框的值,以及如何获取?
I ask if there are a possibility to get the value of the checkedbox in the controller or not, and how?
推荐答案
现在可能有点晚了,但我的经验可能与您的问题有关,或者可以帮助其他有类似问题的人.
It may be a bit late now, but my experience may relate to your issue, or may help someone else with a similar issue.
在我的例子中,复选框被添加到 FormType 中,但如果添加到 FormType 之外,将会呈现我想象的相同.
In my case, the checkbox is added to the FormType, but would present the same I imagine if added outside of the FormType.
我使用表单来处理 REST API 请求,复选框是字段之一.提交表单时,标题包含 'Content-Type': 'application/x-www-form-urlencoded'
所以我可以用 Symfony 表单处理它.
I'm using the form to handle a REST API request, and the checkbox is one of the fields. When the form is submitted, the header includes 'Content-Type': 'application/x-www-form-urlencoded'
so I can handle it with a Symfony form.
这个问题是表单值作为字符串提交(包括复选框值).在 Symfony 方面,它期望如果 checkbox 属性存在 - 它是一个真实"值,如果它不存在,则复选框为 false.但是,因为复选框值可以通过 API 表单作为字符串false"提交 - 这等同于 true - 所以无论是否选中复选框,该值始终为 true.
The issue with this is the form values are submitted as strings (including checkbox values). On the Symfony side, it expects that if the checkbox property exists - it's a 'truthy' value, if it doesn't exist, the checkbox is false. However because the checkbox value can be submitted as the string "false" through the API form - this equates to true - so the value is always true no matter if the checkbox is checked or not.
处理此问题的一种方法(但可能会限制 FormType 的重复使用)是在表单生成器中将复选框类型从复选框"更改为文本":
One way to handle this (but may limit re-use of the FormType) is to change the checkbox type from 'checkbox' to 'text' in the Form Builder:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('my_checkbox', 'text', array('error_bubbling' => true,'required' => false))
...
然后处理表单(并获取 Checkbox 值)
Then processing the form (and getting the Checkbox value)
$form = $this->createForm(new MyFormType(), $myObject);
$form->handleRequest($request);
if($form->isValid()) {
$data = $form->getData();
if($data->getMyCheckbox() === "false") {
$myObject->setMyCheckbox(false);
} else {
$myObject->setMyCheckbox(true);
}
...
这篇关于获取symfony中复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!