php - Symfony 4 - Twig - Forms - 使用 GET 方法发送 FORM 在 URL 中添加括号并包含提交按钮作为参数
问题描述
使用 Symfony 4 使用 GET 方法发送表单时,我遇到了两个问题。此表单包含过滤器,提交此表单会根据所选过滤器更新显示项目的列表。
表单是这样构建的:
class MyForm extends AbstractType {
...
public function buildForm(...) {
$builder
->setMethod("GET")
->add(
"first_filter",
ChoiceType::class,
...
)
->add(
"second_filter",
EntityType::class,
...
)
->add(
"button_apply",
SubmitType::class
);
第一个问题,发送表单后,URL 是这样的:
/action?my_form[first_filter]=...&my_form[second_filter]=...
表单名称包含在每个字段名称之前是否正常,为什么 URL 不能简单地是:
/action?first_filter=...&second_filter=...
第二个问题是提交按钮是 URL 中可见的参数的一部分:
/action?my_form[button_apply]=&...
据我所知,提交按钮本身不应该是一个参数?
提前致谢
解决方案
这是正常的行为,它可以被规避,但它需要调用createNamed
而不是create
表单工厂(参见ControllerTrait::createForm)......所以Symfony\Component\Form\FormFactory::createNamed())
// at the top: use Symfony\Component\Form\FormFactory
public function yourControllerAction(FormFactory $formFactory, Request $request) {
$form = $formFactory->createNamed(
'', // form name, otherwise form class name camel_cased
YourFormType::class, // your form type
[], // initial data or object or whatever!
[] // form options
);
// rest of the script is identical, it's still a normal form
}
或者你不注入它并做特征做的事情:
$form = $this->container->get('form.factory')->createNamed(
// parameters same as before
);
为了使按钮从 GET/POST 中消失,我建议您从表单中删除该按钮,而是将其添加到您的模板中(也增加了可重用性)。
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit">{{ 'your label'|trans }}</button>
{{ form_end(form) }}
这使得按钮提交表单,但由于它没有名称和值,它不会添加到数据中(与SubmitType
按钮表单类型相反)。
推荐阅读
- flutter - Flutter - 动态变化的文本无状态或有状态?
- flutter - 如何在列表选项卡颤动的尾随部分添加两个按钮
- java - VSCode,Gradle,Spring Boot,无法导入 javax.validation
- swift - SwiftUI:ObservableObject 不适用于 fetchRequest init
- android - 关于 Jetpack 寻呼的问题
- reactjs - 如何使用 Ant Design 为 IconFont 自定义颜色
- php - 表单返回错误请求:缺少必需参数:id
- python - InvalidArgumentError Traceback(最近一次调用最后一次)
在 - java - 如何等到 ViewModel 的 LiveData 被检索到
- vba - 访问文本框值