Nespony
Nespony

Reputation: 1371

Access Item By Id in Symfony?

I have a controller in Symfony3. All of the data is returned like this:

  [
{
    "id": 13,
    "name": "testing",
    "entry_date": {
        "date": "2017-12-20 15:23:59.000000",
        "timezone_type": 3,
        "timezone": "Europe/London"
    },
    "last_update": {
        "date": "2017-12-20 15:23:59.000000",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }
},
{
    "id": 30,
    "name": "testing2",
    "entry_date": {
        "date": "2017-12-20 22:02:37.000000",
        "timezone_type": 3,
        "timezone": "Europe/London"
    },
    "last_update": {
        "date": "2017-12-20 22:02:37.000000",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }
}
]

I am trying to return an individual item by their id. My method so far looks like this:

 /**
 * @Method("GET")
 * @Route("/item/{item_id}")
 * @View()
 * @ApiDoc(
 *   resource = true,
 *   description = "Get an item record",
 *   section = "Spark DTR",
 *   )
 */
public function getItem($item_id)
{
  $em = $this->getDoctrine()->getManager('app');
  $mi_repo = $em->getRepository('AppBundle:Item')->find($item_id);

  if(empty($mi_repo)) {
      return new JsonResponse("Invalid Item ID", 404);
  }

  return new JsonResponse($mi_repo, 200);
}

However this method currently returns either "Invalid Item ID" (if there is no item, or

{} 

if there is an item! I want to return the contents of the item. Grateful for your help,

Upvotes: 1

Views: 286

Answers (1)

Caitlyn
Caitlyn

Reputation: 116

With

$em->getRepository('AppBundle:Item')->find($item_id);

You're getting an object as a result, and JsonResponse() is expecting an array as a parameter.

You've got a couple options here. You can install the serializer component (https://symfony.com/doc/3.4/components/serializer.html) and serialize the object directly to Json and return that

$jsonContent = $serializer->serialize($mi_repo, 'json');

OR if you don't want to set up the serializer, you can also use the Doctrine Query Builder with getArrayResult() to return an array instead of an object

$query = $em->createQueryBuilder()
        ->select('p')
        ->from('Products', 'p')
        ->where('p.id= :item_id')
        ->setParameter('id', $item_id)
        ->getQuery();
$mi_repo = $query->getArrayResult();

Hope this helps!

Upvotes: 3

Related Questions