1

How to allow views to export paging data along with entities?

I can set pager, and it works of course, for example my_view?page=1 displays something like

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

but I only get list of filtered or paginated entities, and I would like to include paging information, something like

[ 
  paging_info: [
    total: 4,
    per_page: 2,
    current_page: 1,
    ...
  ],
  data: [
    {...},
    {...}
  ]
]
1

Enable pager Exposed option "Allow user to control the number of items displayed in this view" in rest display, then build custom module with views style plugin - to return results and pager data, and set in rest display

short code from custom style plugin:

$ret = $this->serializer->serialize(
 [
   'results' => $rows,
   'pager' => [
     'count' => $count,
     'pages' => $pages,
     'items_per_page' => $items_per_page,
     'current_page' => $current_page,
   ]
 ],
 $content_type
);

full code in gist: https://gist.github.com/svetlio/79f3c32667b21d89ed03cdb660308668

thanks to Dan's post here: https://www.mediacurrent.com/blog/8-insights-and-useful-snippets-d8-rest-module

0

So as a temp solution I ended up creating custom route which executes the view I want and returns JSON response. So in a controller method I have something like this

$view = \Drupal\views\Views::getView('MY_VIEW_NAME');
//...
$view->executeDisplay('MY_VIEW_DISPLAY_NAME');

$rendered = $view->render();
$json = $rendered['#markup']->jsonSerialize();
$data = json_decode($json);

$pager = [
  'total_rows' => $view->total_rows,
  //...
];

return new JsonResponse([$pager, $data]);

I wont mark this as an answer because I'm sure there is better way of getting desired output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.