mario
mario

Reputation: 624

Symfony2. json output, serialize

a Symfony2 newbie question.

What do I miss in the following code (it returns a "Call to a member function getArrayResult() on a non-object)"

 /**
 * Lists all Post entities.
 *
 * @Route("/jsonout", name="Mario_Post_jsonout")
 * @Method("GET")
 * @Template()
 */
public function jsonoutAction()
{
  $response = new Response();

  $em = $this->getDoctrine()->getEntityManager();
  $query = $this->getDoctrine()
           ->getRepository('MarioBlogBundle:Post')
           ->createQueryBuilder('e')
           ->select('e')
           ->getQuery();

  $results = $query->execute();    
  $myArray = $results->getResult(Query::HYDRATE_ARRAY);  // neither ->getArrayResult(); 
  $response->setContent(json_encode($myArray));
  $response->headers->set('Content-Type', 'application/json');
  return $response;
}

Do I need to use a 'use Doctrine\ORM.....;' line? which one exactly? Thanks

Upvotes: 0

Views: 1143

Answers (2)

Javad
Javad

Reputation: 4397

Two suggestions:

1) You do not need to execute query, you can just say $query->getResult() which will return array of objects. If you want to have results as pure array you can use $query->getArrayResult() which will return array of found values. You also do not need to use select('e') if you want to select all columns.

2) If you want to get all records without any criteria and condition you can use findAll(); which return array of all objects in your entity:

$em = $this->getDoctrine()->getEntityManager();
$results = $em->getRepository('MarioBlogBundle:Post')->findAll();

Now by installing and using this class EntitySerializer you can have array output or just JSON output (which you want). For your example it will be:

$entitySerializer = new Bgy\Doctrine\EntitySerializer($em);
$jsonOutput = $entitySerializer->toJson($results);

Upvotes: 0

Nisam
Nisam

Reputation: 2285

From my experience the methods getResult() and getArrayResult() coming with the $query object not with $result object. So we don't want to use both ->execute() and getResult() together. That's the mistake in your code. we can rewrite your code like,

public function jsonoutAction()
{
  $response = new Response();

  $em = $this->getDoctrine()->getEntityManager();
  $query = $this->getDoctrine()
           ->getRepository('MarioBlogBundle:Post')
           ->createQueryBuilder('e')
           ->select('e')
           ->getQuery();

  $results = $query->getArrayResult();    //or   getResult(Doctrine\ORM\Query::HYDRATE_ARRAY);

  $response->setContent(json_encode($results));
  $response->headers->set('Content-Type', 'application/json');
  return $response;
}

it will get worked.

Upvotes: 2

Related Questions