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?
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;
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With