8

I am using this:

    $users = $em->getRepository('UserBundle:User')->getallUsers($search);
    $response = new Response(json_encode($users));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

Users are multiple entities not single result.

But I am getting this:

[{},{},{},{},{},{}]

I want something like:

[ { label: $user.getName(), value: $user.getId() }, ... ]

How can i do that?

EDIT: I also tried json_encode($users->toArray()) then I get this error:

Call to a member function toArray() on a non-object

1
  • 1
    Which version of symfony do you use? Commented Aug 8, 2012 at 5:55

2 Answers 2

6

You need to have a way to serialize your objects, you can't expect json_encode to magically guess which fields are allowed to be encoded.

A good bundle I recommend for this task is JMSSerializerBundle. Make sure you read through documentation carefully before using it!

End result will probably look like this:

$users = $em->getRepository('UserBundle:User')->getallUsers($search);
$response = new Response($container->get('serializer')->serialize($users, 'json'));
Sign up to request clarification or add additional context in comments.

5 Comments

I already jave JMSSerializerBundle installed but i get this error You have requested a non-existent service "serializer". how can i declrae the service for JMS
it is there in jms vendor and its latest version
You have to register the bundle in your app/AppKernel.php
You can try : $serializer = $this->container->get('serializer'); $response = new Response($serializer->serialize($users, 'json'));
@Inoryy you miss the $this before container
0

Try {{ your_variable|raw }}

Sorry for late

1 Comment

Well this is the best easy method, but it is not automatic and requires implementing __toString() function in a class, which returns json_serialize(array(..)) product.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.