Magento, Magento 2

How to Add Pagination to Custom Collection in Magento 2

How to Add Pagination to Custom Collection in Magento 2

In this tutorial, Today I will explain to how to add pagination to custom collection in Magento 2. Whenever you have large number of records in your collection at that time, we should add pagination so, page load will be increase and limited records only display when page load.

So, How to add in your custom collection. Let’s follow the below step for that.

You may also like this :

1) First of all, Let’s assume that you have created simple module for that. Then, create Helloworld.php block file at app/code/RH/Helloworld/Block/ and paste the below code :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $productFactory;
    
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Model\ProductRepository         $productRepository
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        array $data = []
    ) {
        $this->productFactory = $productFactory;
        parent::__construct($context, $data);
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        $this->pageConfig->getTitle()->set(__('My Pagination'));
        if ($this->getProductCollection()) {
            $pager = $this->getLayout()->createBlock(
                'Magento\Theme\Block\Html\Pager',
                'custom.history.pager'
            )->setAvailableLimit([5 => 5, 10 => 10, 15 => 15, 20 => 20])
            ->setShowPerPage(true)->setCollection(
                $this->getProductCollection()
            );
            $this->setChild('pager', $pager);
            $this->getProductCollection()->load();
        }
        return $this;
    }

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

    public function getProductCollection()
    {
        $page = ($this->getRequest()->getParam('p')) ? $this->getRequest()->getParam('p') : 1;
        $pageSize = ($this->getRequest()->getParam('limit')) ? $this->getRequest()->getParam('limit') : 5;
        $collection = $this->productFactory->create()->getCollection();
        $collection->setPageSize($pageSize);
        $collection->setCurPage($page);
        return $collection;    
    }

}

2) Then, Create Index.php Controller file at app/code/RH/Helloworld/Controller/Index/ and paste the below code :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Action;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('Welcome to RH Helloworld module'));
        return $resultPage;
    }
}

3) Then, Create helloworld_index_index.xml layout file at app/code/RH/Helloworld/view/frontend/layout/ and paste the below code :

<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="columns.top">
            <block class="Magento\Theme\Block\Html\Title" name="page.main.title" template="html/title.phtml"/>
            <container name="page.messages" htmlTag="div" htmlClass="page messages">
                <block class="Magento\Framework\View\Element\Template" name="ajax.message.placeholder" template="Magento_Theme::html/messages.phtml"/>
                <block class="Magento\Framework\View\Element\Messages" name="messages" as="messages" template="Magento_Theme::messages.phtml"/>
            </container>
        </referenceContainer>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">RH Custom Pagination</argument>
            </action>
        </referenceBlock>
        <referenceBlock name="content">
            <block class="RH\Helloworld\Block\Helloworld" name="custom.pagination" template="RH_Helloworld::helloworld.phtml" />
        </referenceBlock>
    </body>
</page>

4) In Last, Create helloworld.phtml template file at app/code/RH/Helloworld/view/frontend/templates/ and paste the below code :

<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif ?>
<?php $productColl = $block->getProductCollection(); ?>
<?php if ($productColl && count($productColl->getData() > 0)): ?>
<div class="table-wrapper orders-history">
    <table class="data table table-order-items history" id="rh-pagination">
        <caption class="table-caption"><?php echo __('Custom Collection Records') ?></caption>
        <thead>
            <tr>
                <th scope="col" class="col id"><?php echo __('ID') ?></th>
                <th scope="col" class="col product-name"><?php echo __('Product Name') ?></th>
                <th scope="col" class="col sku"><?php echo __('Sku') ?></th>
                <th scope="col" class="col price"><?php echo __('Price') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($productColl as $product): ?>
            <tr>
                <td data-th="<?= $block->escapeHtml(__('ID')) ?>" class="col id">
                    <?php echo $product->getId(); ?>
                </td>
                <td data-th="<?= $block->escapeHtml(__('Product Name')) ?>" class="col product-name">
                    <?php echo $product->getProductName(); ?>
                </td>
                <td data-th="<?= $block->escapeHtml(__('Sku')) ?>" class="col sku">
                    <?php echo $product->getSku(); ?>
                </td>
                <td data-th="<?= $block->escapeHtml(__('Price')) ?>" class="col price">
                    <?php echo $product->getPrice(); ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php if ($block->getPagerHtml()): ?>
    <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif ?>
<?php else: ?>
    <div class="message info empty"><span><?php echo __('You have no any records in your custom collection.'); ?></span></div>
<?php endif ?>

That’s it !!!

Now, you can see pagination display in your grid.

I hope this blog is easy to understand about how to add pagination to custom collection in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged ,