Skip to content

Instantly share code, notes, and snippets.

@shelane
Forked from purushotamrai/DrupalCallback.php
Created July 19, 2023 19:10
Show Gist options
  • Save shelane/771df3f76d6b62dd86a6c8f10ada2bda to your computer and use it in GitHub Desktop.
Save shelane/771df3f76d6b62dd86a6c8f10ada2bda to your computer and use it in GitHub Desktop.
Implementing Custom Pagination without Drupal Entity Query - Drupal 8
<?php
namespace Drupal\custom_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Pager\PagerManagerInterface;
class ListNonDrupalItems extends ControllerBase {
/**
* Drupal\Core\Pager\PagerManagerInterface definition.
*
* @var \Drupal\Core\Pager\PagerManagerInterface
*/
protected $pagerManager;
public function __construct(PagerManagerInterface $pagerManager) {
$this->pagerManager = $pagerManager;
}
public static function create(ContainerInterface $container) {
$instance = $container->get('pager.manager');
return new static($instance);
}
public function build() {
$build = [];
// Get data.
$items = $this->getBigListData();
$total = count($items);
$limit = 10;
// Initialize pager and get current page.
$pager = $this->pagerManager->createPager($totalFiles, $limit);
$currentPage = $pager->getCurrentPage();
// Use currentPage to limit items for the page.
$items = array_slice($items, $currentPage * $limit, $limit);
$build['list'] = [
'#theme' => 'item_list',
'#list_type' => 'ol',
'#title' => 'List',
'#items' => [],
];
// Display items.
foreach ($items as $item) {
$build['list']['#items'][] = [
'#wrapper_attributes' => [
'class' => ['item'],
],
'#children' => $item,
];
}
$build['pager'] = [
'#type' => 'pager',
];
return $build;
}
private function getBigListData() {
return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment