I want to convert data object to json form, this is my code in symfony,
$connection = $em->getConnection();
$statement = $connection->prepare("select * from contact where id_user=$id");
$statement->execute();
$contacts = $statement->fetchAll();
and in rendering object, I do this,
return $this->render('...index.html.twig', array('form' => $form->createView(), 'errors' => $form->getErrors(), 'contacts'=>json_encode($contacts)));
but this does not work, any help please
Try this:
$contacts= json_encode($contacts);
$Response = new Response(
'...myTemplate.html.twig',
['form' => $form->createView()],
['errors' => $form->getErrors()],
['contacts' => $contacts]
);
$Response->headers->set('Content-Type', 'application/json');
return $oResponse;
Don't forget to use:
use Symfony\Component\HttpFoundation\Response;
Or you can use the JsonResponse Class. Here's the documentation: symfony doc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.