0

I have the following code:

public function adminListAction(Request $request)
{
    if (!$this->isGranted('ROLE_ADMIN')) {
        return new JsonResponse("Not granted");
    }

    $page = $request->query->get('page', 1);

    $criteria = new DocumentaryCriteria();
    $criteria->setStatus(DocumentaryStatus::PUBLISH);
    $criteria->setSort([
        DocumentaryOrderBy::CREATED_AT => Order::DESC
    ]);

    $qb = $this->documentaryService->getDocumentariesByCriteriaQueryBuilder($criteria);

    $adapter = new DoctrineORMAdapter($qb, false);
    $pagerfanta = new Pagerfanta($adapter);
    $pagerfanta->setMaxPerPage(12);
    $pagerfanta->setCurrentPage($page);

    $items = (array) $pagerfanta->getCurrentPageResults();

    $data = [
        'items'             => $items,
        'count_results'     => $pagerfanta->getNbResults(),
        'current_page'      => $pagerfanta->getCurrentPage(),
        'number_of_pages'   => $pagerfanta->getNbPages(),
        'next'              => ($pagerfanta->hasNextPage()) ? $pagerfanta->getNextPage() : null,
        'prev'              => ($pagerfanta->hasPreviousPage()) ? $pagerfanta->getPreviousPage() : null,
        'paginate'          => $pagerfanta->haveToPaginate(),
    ];

    return new JsonResponse($data);
}

which returns the following, notice the array of empty objects

{ "items": [ {}, {}, {}, {}, {}, {}, {}, {}, {} ], "count_results": 9, "current_page": 1, "number_of_pages": 1, "next": null, "prev": null, "paginate": false }

I know their properties aren't null by doing this:

foreach ($items as $item) {
    echo $item->getTitle();
}

// returns 'Documentary 1'

Oliver Lorton
  • 709
  • 1
  • 6
  • 21
JonnyD
  • 73
  • 2
  • 9
  • The problem is as Erik Baars is stating. The items in the array are not Serializable to JSON. Try `$items = iterator_to_array($pagerfanta->getCurrentPageResults());` instead of casting it to an array. – Bas Matthee Jul 10 '19 at 13:00

1 Answers1

0

The problem is most likely that your $item object is not json serializable.

Try implementing the JsonSerializable interface in that class(https://www.php.net/manual/en/class.jsonserializable.php) and add a method to your item class like so:

public function jsonSerialize() {
    return [
        'title' => $this->getTitle(),
         'foo' => $this->bar(),
     ];
 }
Oliver Lorton
  • 709
  • 1
  • 6
  • 21
Erik Baars
  • 2,278
  • 1
  • 8
  • 14