Skip to content

Instantly share code, notes, and snippets.

@phunguyen19
Forked from shadcn/SerializerWithPager.php
Last active June 10, 2022 13:42
Show Gist options
  • Save phunguyen19/855596ecdcb3c32bacbb00e2eb2f9203 to your computer and use it in GitHub Desktop.
Save phunguyen19/855596ecdcb3c32bacbb00e2eb2f9203 to your computer and use it in GitHub Desktop.
drupal 8 View plugin Serializer with paging
<?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]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment