Reputation: 31
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?
Upvotes: 3
Views: 3541
Reputation: 1873
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;
}
Upvotes: 3
Reputation: 31
Formtype getName method was returning formtype name, changed that to table name. Its working now. Thanks.
Upvotes: 0
Reputation: 22817
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());
}
Upvotes: 1