2
votes

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

  • Entity class is Version.php
  • Custom repository is VersionRepository

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 !

1
You need to tell json_encode which data of your objects to serialize. You actually have a lot of options: use the JMSSerializerBundle and the annotations this library provides, build your own serializer(symfony.com/doc/current/components/serializer.html) or the simplest to implement JsonSerializable for your entity(stackoverflow.com/questions/47335932/…). - Jannes Botis
As suggested by @ASOlivieri I tried JMS with success. Thanks for the tip ! - Paolito75

1 Answers

1
votes

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.