Search code examples
phpjsonsymfonydoctrineserver-side

How can I get data from mysql database with json encode (Symfony 4)?


Right now I am getting data from the database via Doctrine:

$articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
return $this->render('homepage.html.twig', array('articles' => $articles));

This is working fine. But what I need is to get the data via json encode, because I want to use server-side processing datatables. So I try to use the Serializer

  $encoders = array(new XmlEncoder(), new JsonEncoder());
  $normalizers = array(new ObjectNormalizer());

  $serializer = new Serializer($normalizers, $encoders);
  $articles = $this->getDoctrine()->getRepository(Article::class)->findAll();
  $jsonContent = $serializer->serialize($articles, 'json');

  return $this->render('homepage.html.twig', $jsonContent);

But I get the error message:

Argument 2 passed to Symfony\Bundle\FrameworkBundle\Controller\AbstractController::render() must be of the type array, string given, called in /Users/work/project/src/Controller/ArticleController.php on line 46 Uncaught PHP Exception Symfony\Component\Debug\Exception\FatalThrowableError: "Argument 2 passed to Symfony\Bundle\FrameworkBundle\Controller\AbstractController::render() must be of the type array, string given, called in /Users/work/project/src/Controller/ArticleController.php on line 46" at /Users/work/project/vendor/symfony/framework-bundle/Controller/ControllerTrait.php line 219


Solution

  • So make second argument of render an array:

    return $this->render('homepage.html.twig', ['json_content' => $jsonContent]);
    

    In a template:

    {{ json_content }}
    

    Though I don't know why you use a template, as there's a json() method which returns single json:

    return $this->json($articles); // without using serializer