Paolito75
Paolito75

Reputation: 568

Symfony - findAll() returns ok if render, empty if response

I created a custom Bundle in my Symfony 2.7 website. One of the entity works perfectly :

The MainController.php of my bundle is :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return $this->render('IpadUpdaterBundle:Version:index.html.twig', array(
'versions' => $versions
));

Output in Twig is perfect :

  • My first version row
  • My second version row

BUT ... if I want to change the ouput and render a JSON response with the same datas, I make this change in the controller :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

$versions = json_encode($versions);
$rep_finale = new Response($versions);
$rep_finale->headers->set('Content-Type', 'application/json');
return $rep_finale;

or :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return new JsonResponse($versions);

.. and the ouput becomes an empty array with 2 children :

[{},{}]

!I can not understand what's wrong and what changes I would implement to solve this issue. I already use "use Symfony\Component\HttpFoundation\Response" and "use Symfony\Component\HttpFoundation\JsonResponse" in the header of my controller.php.

Thanks for your help !

Upvotes: 3

Views: 2956

Answers (1)

Ollie in PGH
Ollie in PGH

Reputation: 2629

json_encode and JSONResponse don't do well with complex entities, especially with links to other complex entities. Mostly, those are for encoding strings or arrays as JSON.

If you only need some of the information from your entities you can make an array and pass that.

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versionInformation = $repository->getIdNameOfVersionsAsArray();
$versionInformation = array_column($versionInformation, 'id', 'name');

return new JSONResponse($versionInformation);

You'll have to implement the getIdNameOfVersionsAsArray function in your repository to just return an array of values.

If you need every field of your version entity it may be easier to use a serializer. JMSSerializer Bundle is the most popular and well-supported.

$serializer = $this->container->get('serializer');
$versionJSON = $serializer->serialize($versions, 'json');

return new Response($versionJSON);

And you'll have to implement annotations in your entities to tell the serializer what to do. See the link above for that.

Upvotes: 1

Related Questions