【发布时间】:2021-01-23 17:47:46
【问题描述】:
我正在尝试使用以下功能在 Symfony 5 中管理同一页面中的多个表单,但似乎每次我尝试提交表单时,即使不是列表的第一个表单也会被处理已提交的:
class ContentController extends AbstractController
{
/**
* @Route("/category/edition/{content}", name="edit_category")
*/
public function edition(Request $request, Category $content): Response
{
$forms = [
"edit_category" => $this->createForm(EditCategoryType::class, $content),
"create_post" => $this->createForm(CreatePostType::class)
];
foreach($forms as $form) {
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
// Always prints edit_category
// even when that is the the create_post that is submitted
return var_dump($form->getName());
}
}
return $this->render(
'content/edition.html.twig',
[
'forms' => \array_map(
function($form) {
return $form->createView();
},
$forms
),
'content' => $content,
]
);
}
}
我在其他帖子中看到表单的名称有时会引发问题,但我已经检查过表单确实有不同的名称,并且我还尝试在单独的 @ 中对每个表单调用 handleRequest() 987654323@ 循环,因为我在一些帖子中看到过这样做,但它(我必须说非常符合预期)并没有改变行为。
而且我似乎没有找到任何关于如何在 Symfony 的同一个控制器中处理多个表单的一致最佳实践技巧,所以我想知道最好的方法是什么,或者定义是否更清晰为每个表单设置单独的操作路线,以完全避免此问题。
如果需要,content/edition.html.twig 文件看起来像这样:
{% set edit_category_form = forms['edit_category'] %}
{% set create_post_form = forms['create_post'] %}
{{ form_start(edit_category_form) }}
{{ form_errors(edit_category_form) }}
{{ form_end(edit_category_form) }}
{{ form_start(create_post_form) }}
{{ form_errors(create_post_form) }}
{{ form_end(create_post_form) }}
(Category 是一个经典的 Symfony 实体,EditCategoryType 是与 Category 实体关联的表单,CreatePostType 是与另一个 Symfony 实体关联的表单)
【问题讨论】:
-
是否可以编辑您的帖子,使代码成为可运行的 sn-p 供其他用户测试?
-
我没有包含表单和实体类,因为它们不相关,但现在可能会更好。
标签: symfony