Created
April 25, 2020 21:15
-
-
Save purushotamrai/1d16bf382cf7d44bb856484bfab6f486 to your computer and use it in GitHub Desktop.
Implementing Custom Pagination without Drupal Entity Query - Drupal 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
there is one mistake with variable name $totalFile should rename with $total.