Magento 2 add pagination custom collection

Today we talk about Magento 2 add pagination custom collection. we’ll talk about how to get custom collection with magento 2 default pagination or use pager with custom collection.For any suggestions & question, please feel free to drop a comment.

First Step:

Get collection for pagination.

public function getNews() {
 //get values of current page
$page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
 //get values of current limit
$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;
$newsCollection = $this->newscollectionFactory->create(); $newsCollection->addFieldToFilter('is_active',1); $newsCollection->setOrder('title','ASC'); $newsCollection->setPageSize($pageSize); $newsCollection->setCurPage($page);
return $newsCollection;
}

Second Step:
Now simply add the pagination to you collection

protected function _prepareLayout() {
parent::_prepareLayout();
$this->pageConfig->getTitle()->set(__('News'));
 if ($this->getNews()) {
$pager = $this->getLayout()->createBlock( 'Magento\Theme\Block\Html\Pager', 'qaisarsatti.news' )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection( $this->getNews() );
$this->setChild('pager', $pager);
$this->getNews()->load();
}
return $this;
}

Third Step:
Now create a function to get the child block of pager.

public function getPagerHtml() {
return $this->getChildHtml('pager');
 }

Fourth Step:
in your phtml file add this code then pagination will be showing with limits.

<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif ?>

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply