Skip to content

Instantly share code, notes, and snippets.

@shadcn
Created December 20, 2016 06:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shadcn/2ab016c87f31cfd27d16c283cc610ca4 to your computer and use it in GitHub Desktop.
Save shadcn/2ab016c87f31cfd27d16c283cc610ca4 to your computer and use it in GitHub Desktop.
A views Serializer plugin for Drupal 8 with pager
<?php
namespace Drupal\MODULE_NAME\Plugin\views\style;
use Drupal\rest\Plugin\views\style\Serializer;
/**
* The style plugin for serialized output formats with pager.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "serializer_with_pager",
* title = @Translation("Serializer with pager"),
* help = @Translation("Serializes views row data using the Serializer component with pager."),
* display_types = {"data"}
* )
*/
class SerializerWithPager extends Serializer {
/**
* {@inheritdoc}
*/
public function render() {
$rows = array();
// If the Data Entity row plugin is used, this will be an array of entities
// which will pass through Serializer to one of the registered Normalizers,
// which will transform it to arrays/scalars. If the Data field row plugin
// is used, $rows will not contain objects and will pass directly to the
// Encoder.
foreach ($this->view->result as $row_index => $row) {
$this->view->row_index = $row_index;
$rows[] = $this->view->rowPlugin->render($row);
}
unset($this->view->row_index);
// Get the content type configured in the display or fallback to the
// default.
if ((empty($this->view->live_preview))) {
$content_type = $this->displayHandler->getContentType();
}
else {
$content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
}
$results = [
'results' => $rows,
];
// Add pager information to the rows.
$pager = $this->view->pager;
$results['pager'] = [
'current_page' => $pager->getCurrentPage(),
'items_per_page' => $pager->getItemsPerPage(),
'total_items' => $pager->getTotalItems(),
];
return $this->serializer->serialize($results, $content_type, ['views_style_plugin' => $this]);
}
}
@phunguyen19
Copy link

Thanks Arshad, your snippet works great, it saves my day.

@julianca897
Copy link

Hi, I need a little bit information about to where I should put this file(the path).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment