I'm trying to return the users like this, but of course it doesn't work, I need the data as JSon since im working with BackboneJs
/**
* @Route("/mytest",name="ajax_user_path")
*/
public function ajaxAction()
{
$em = $this->get('doctrine')->getManager();
$users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();
$response = array("users"=>$users);
return new Response(json_encode($response));
}
So,
findAll
returns an array of entities (objects) andjson_encode
cannot correctly encode that array. You have to prepare your data berofe send response like that:Example:
Moreover, it would be great if you put preparing response to ex.
UserRepository
class.I have never tried to encode a complete object, but I have used json with arrays of informations like this:
As you can see in JsonResponse, its function
setData()
is encoding the array, so you don't have to do it yourself:With Symfony you have JsonResponse like :
And don't forget to add the header :
Thanks for your help guys, here is the Solution Get the JMSSerializerBundle,
This is the code on the controller