Symfony中的表单无效,没有错误


Invalid Form in Symfony with no errors

这是我第一次尝试在Symfony中使用表单,我完全陷入了困境。 我相信这将是一件简单的事情。

我有一个简单的控制器设置如下(使用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"
}

希望能帮助其他人避免兔子洞,我以艰难的方式发现了这个!

默认情况下,Symfony会自动为您嵌入并验证CSRF令牌,因此错误可能是因为未提供令牌。

阅读更多:

http://symfony.com/doc/current/book/forms.html#csrf-protection