这是我第一次尝试在 Symfony 中使用表单,我完全被困住了。我相信这会很简单。
我有一个简单的 Controller 设置(使用 Symfony 2.7 和 FOSRestBundle 2.0):
/**
* @View()
*/
public function postPredictionsAction(Request $request)
{
$form = $this->createFormBuilder(['id' => '1', 'description' => '2'])
->add('id', 'text')
->add('description', 'text')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
return true;
}
print_r($request->request->all());
print_r($form->getData());
print_r((string) $form->getErrors(true, false));
return false;
}
但是我的表单总是无效的,即使没有错误:
curl -X POST --data 'id=foo&description=bar' http://localhost:8080/bracket/predictions
Array
(
[id] => foo
[description] => bar
)
Array
(
[id] => 1
[description] => 2
)
false
所以看起来我的请求数据没有进入表单,并且由于某种原因表单无效,即使根本没有打印错误。
编辑:经过大量的讨论之后,handleRequest()
调用似乎已确定表单尚未提交,因此未经过验证 - 这意味着我进入了这种情况如上所述。
因此,我可以用 submit()
代替 handleRequest()
作为变通方法。这被文档描述为已弃用的行为:
http://symfony.com/doc/2.7/cookbook/form/direct_submit.html#cookbook-form-submit-request
所以我显然仍然做错了什么,但我无法从 Symfony 文档中看到它是什么。
最佳答案
我已经确定问题所在。
当像我一样发布数据时,默认情况下 Symfony 期望它被封装在表单的名称中。例如,使用 JSON:
{
"form": {
"id": "12",
"name": "abc"
}
}
现在对于 RESTful API 这不是我想要的(我也不怀疑大多数人想要或期望的行为),因此您可以在代码中执行以下操作:
/**
* @View()
*/
public function postPredictionsAction(Request $request)
{
$form = $this->createFormBuilder(['id' => '1', 'description' => '2'])
->add('id', 'text')
->add('description', 'text')
->getForm();
// NOTE: we use submit here, but pass the data as an array, thus
// making it Symfony 3 compatible
$form->submit($request->request->all());
if ($form->isValid()) {
// Do valid work
}
// Output validation errors
return $form;
}
这与以下 JSON 一起工作得很好:
{
"id": "12",
"name": "abc"
}
希望这能帮助其他人避开我在艰难的过程中发现的兔子洞!
关于php - Symfony 中的无效表单,没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36090165/