Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOSRestBundle json decode issue

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?

like image 542
user1844391 Avatar asked Feb 23 '26 08:02

user1844391


2 Answers

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;
}
like image 56
Dayson Avatar answered Feb 25 '26 03:02

Dayson


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());
}
like image 30
moonwave99 Avatar answered Feb 25 '26 03:02

moonwave99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!