Pagination is already present on Magento 2 default collections. However, incase of custom collection in Magento 2 such as image galleries, product collection, etc. pagination has to be added. In the following tutorial we have shown how you can add Magento 2 pagination to your custom collections through a simple step by step guide. Although there are multiple approaches to achieve this, we have shown the most effective and easy method for pagination of your Magento 2 custom collection.
You can also seek assistance about Magento web development from FMEextensions that are not only limited to setting up a website, as our services extends to consultancy, installation, and customization to your business needs.protected $newscollectionFactory; public function __construct(\FME\News\Model\ResourceModel\News\CollectionFactory $newscollectionFactory) { $this->newscollectionFactory = $newscollectionFactory; } public function getNews() { //get values of current page. if not the param value then it will set to 1 $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1; //get values of current limit. if not the param value then it will set to 1 $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1; $newsCollection = $this->newscollectionFactory->create(); $newsCollection->setPageSize($pageSize); $newsCollection->setCurPage($page); return $newsCollection; }
protected function _prepareLayout()
{
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('News'));
if ($this->getNews()) {
$pager = $this->getLayout()->createBlock(
'Magento\Theme\Block\Html\Pager',
'fme.news.pager'
)->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection(
$this->getNews()
);
$this->setChild('pager', $pager);
$this->getNews()->load();
}
return $this;
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
<?php if ($block->getPagerHtml()): ?> <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div> <?php endif ?>