3

Using FOSRestbundle, trying to insert data into table using POST and content-type as application/json. My config.yml has the following

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

In controller added something like this

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

But getting null values for all the DB fields. Any idea?

astorije
  • 2,666
  • 2
  • 27
  • 39
user1844391
  • 31
  • 1
  • 4

3 Answers3

3

FOSRestBundle's Body Listener already json decodes the request content and stores it in the Request parameter bag. You can access the json decoded array using

$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;
}
epicwhale
  • 1,835
  • 18
  • 26
1

Though it's Silex tailored, this should fix your problem:

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());
}
moonwave99
  • 21,957
  • 3
  • 43
  • 64
0

Formtype getName method was returning formtype name, changed that to table name. Its working now. Thanks.

user1844391
  • 31
  • 1
  • 4