Skip to content

Instantly share code, notes, and snippets.

@purushotamrai
Created April 25, 2020 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save purushotamrai/1d16bf382cf7d44bb856484bfab6f486 to your computer and use it in GitHub Desktop.
Save purushotamrai/1d16bf382cf7d44bb856484bfab6f486 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'];
}
}
@Atul-Ghate
Copy link

there is one mistake with variable name $totalFile should rename with $total.

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