3

使用FOSRestbundle,尝试使用 POST 和 content-type as 将数据插入表中application/json。我config.yml的有以下

fos_rest:
  param_fetcher_listener: true
  body_listener: true
  format_listener:
    default_priorities: ['json', html, '*/*']
    prefer_extension: true
  view:
    view_response_listener: force
    failed_validation: HTTP_BAD_REQUEST
    default_engine: php
  formats:
    json: true

在控制器中添加了这样的东西

$request= $this->getRequest();
$form->bindRequest($request);
$em = $this->get('doctrine')->getEntityManager();
$em->persist($entity);
$em->flush();

但是获取null所有数据库字段的值。任何想法?

4

3 回答 3

3

FOSRestBundle 的 Body Listener 已经对请求内容进行了 json 解码,并将其存储在 Request 参数包中。您可以使用访问 json 解码数组

$request->request->all()

public function postFooAction(Request $request)
{
    if (!$request->getFormat($request->headers->get('Content-Type')) == 'json') {
        throw new BadRequestHttpException("Invalid Content-Type Headers");
    }
    $data = $request->request->all(); // FOSRestBundle's BodyListener sets the Request Parameter Bag to the json decoded data already



    return true;
}
于 2014-05-28T05:33:20.437 回答
1

虽然它是 Silex 量身定制的,但这应该可以解决您的问题:

use Symfony\Component\HttpFoundation\Request;

...

if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());
}
于 2012-11-22T15:32:34.397 回答
0

Formtype getName 方法返回表单类型名称,将其更改为表名称。它现在工作。谢谢。

于 2012-11-24T09:46:15.697 回答