Magento 2 Add Pagination in Custom Collection

Written by Mahesh Makwana

Oct 10, 2020

Magento 2 Add Pagination in Custom Collection

Pagination is the process of separating print or digital content into discrete pages. It is an ordinal numbering of pages, which is usually located at the bottom of the site pages. Pagination also refers to the automated process of adding consecutive numbers to identify the sequential order of pages. Some types of website content benefit from being broken into separate pages to make them more user-friendly, such as search engine results pages (SERP), blogs and discussion forums.

Magento 2 provides the default pagination for the product pages, category pages, My Orders, etc at the frontend. It helps in easy navigation. Moreover, without pagination, the page load time would increase due to a large amount of content, links, etc. on a single page. It affects the user experience of the page and hence degrades the SEO!

Today we will learn how to add custom pagination for custom collection in Magento 2. Before adding the below files create a Model. if you don’t know about to create a model then you can hire our Magento 2 expert.

Please follow the below steps for add custom pagination:

Step-1 : Create controller file Index.php at app/code/Dolphin/CustomModule/Controller/Index and add below code.

<?php

namespace Dolphin\CustomModule\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('Custom Pagination'));
        return $resultPage;
    }
}

Step-2: Create block file Pager.php at app/code/Dolphin/CustomModule/Block and add the below code.

<?php
<?php

namespace Dolphin\CustomModule\Block;

use Magento\Framework\View\Element\Template;

class Pager extends Template
{
    protected $customFactory;
    protected $customdataCollection;

    public function __construct(
        Template\Context $context,
        \Dolphin\CustomModule\Model\CustomData $customFactory, // Add your custom Model
        \Dolphin\CustomModule\Model\ResourceModel\CustomData\CollectionFactory $customdataCollection, // Add your custom Model
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->customFactory = $customFactory;
        $this->customdataCollection = $customdataCollection;
    }
    protected function _prepareLayout()
    {
        $this->pageConfig->getTitle()->set(__('My Custom Pagination'));
        parent::_prepareLayout();
        $page_size = $this->getPagerCount();
        $page_data = $this->getCustomData();
        if ($this->getCustomData()) {
            $pager = $this->getLayout()->createBlock(
                \Magento\Theme\Block\Html\Pager::class,
                'custom.pager.name'
            )
                ->setAvailableLimit($page_size)
                ->setShowPerPage(true)
                ->setCollection($page_data);
            $this->setChild('pager', $pager);
            $this->getCustomData()->load();
        }
        return $this;
    }
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }

    public function getCustomData()
    {
        // get param values
        $page = ($this->getRequest()->getParam('p')) ? $this->getRequest()->getParam('p') : 1;
        $pageSize = ($this->getRequest()->getParam('limit')) ? $this->getRequest()->getParam('limit') : 5; // set minimum records
        // get custom collection
        $collection = $this->customFactory->getCollection();
        $collection->setPageSize($pageSize);
        $collection->setCurPage($page);
        return $collection;
    }

    public function getPagerCount()
    {
        // get collection
        $minimum_show = 5; // set minimum records
        $page_array = [];
        $list_data = $this->customdataCollection->create();
        $list_count = ceil(count($list_data->getData()));
        $show_count = $minimum_show + 1;
        if (count($list_data->getData()) >= $show_count) {
            $list_count = $list_count / $minimum_show;
            $page_nu = $total = $minimum_show;
            $page_array[$minimum_show] = $minimum_show;
            for ($x = 0; $x <= $list_count; $x++) {
                $total = $total + $page_nu;
                $page_array[$total] = $total;
            }
        } else {
            $page_array[$minimum_show] = $minimum_show;
            $minimum_show = $minimum_show + $minimum_show;
            $page_array[$minimum_show] = $minimum_show;
        }
        return $page_array;
    }
}

Here _prepareLayout() method is called immediately after a block has been added to the layout for the first time and set custom pagination with custom data. We are added dynamic pagination count using getPagerCount() method. In this method we set minimum record count 5. You can also change this record count.

Step-3 : Create template file pager.phtml at app/code/Dolphin/CustomModule/view/frontend/templates and add below code.

<?php
// get custom data
$custom_data = $block->getCustomData();
?>
<fieldset class="fieldset">
    <?php
    if (count($custom_data)) {
        ?>
        <div class="table-wrapper custom-data ">
            <table class="data table table-data-items ">
                <caption class="table-caption"><?= $block->escapeHtml('Custom Pagination') ?></caption>
                <thead>
                    <tr>
                        <th scope="col" class="col name"><?= $block->escapeHtml('Name') ?></th>
                        <th scope="col" class="col orders"><?= $block->escapeHtml('Orders') ?></th>
                        <th scope="col" class="col orderitem"><?= $block->escapeHtml('Items') ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($custom_data as $item): ?>
                    <tr>
                        <td data-th="Name" class="col name">
                         <span><?= $block->escapeHtml($item->getName()) ?></span>
                        </td>
                        <td data-th="Orders" class="col orders">
                            <span><?= $block->escapeHtml($item->getOrders()) ?></span>
                        </td>
                        <td data-th="Items" class="col orderitem">
                            <span><?= $block->escapeHtml($item->getOrderItem()) ?></span>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php if ($block->getPagerHtml()): ?>
                <div class="order-products-toolbar toolbar bottom">
                    <?= $block->getPagerHtml() ?>
                </div>
        <?php endif ?>
    <?php } else { ?>
                <div class="message info empty">
                    <span><?= $block->escapeHtml('You have no data in table.') ?></span>
                </div>
    <?php  } ?>
</fieldset>
<?php if ($block->getPagerHtml()): ?>
        <div class="order-products-toolbar toolbar bottom">
            <?= $block->getPagerHtml() ?>
        </div>
<?php endif ?>

Step-4 : Create layout file frontroutename_index_index.phtml at app/code/Dolphin/CustomModule/view/frontend/layout and add below code.

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="customer_account"/>
    <body>
        <referenceContainer name="content">
            <block class="Dolphin\CustomModule\Block\Pager"
                   name="your_block_name"
                   template="Dolphin_CustomModule::pager.phtml"
                   cacheable="false"
                   />
        </referenceContainer>
    </body>
</page>

In this file, name must be like this frontroutename_controllername_actionfilename.xml

Step-5: Run Magento upgrade and flush cache command.

bin/magento setup:upgrade
bin/magento c:f

Step-6: Run below URL

http://<yourhostname.com>/frontroutename/index/index

You custom pagination looks like this :

Add Custom Pagination Magento 2

You also like to read this:

I hope this helps you. For any doubts regarding this topic, please write your doubts in below comments section or CONTACT US

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP