Categories: How ToMagento 2

How to Add Pagination in Custom Collection of Magento 2

Whenever you have dozens of pages of the website content, listing all the links on a single page makes it clumsy and can cause heavy load times. Pagination divides a single piece of content into various pages which directly affect user experience, development of website and SEO.

It is the most common technique of providing navigation. Pagination is already available in default Magento 2 collections like product collection, search collection etc. But recently when we were working on a project of our client, we required to add pagination in custom collection of Magento 2. In order to fulfill this requirement, we dig deeper and went through many approaches, of which the best is what I’m sharing here.

Step by step guide to add pagination in custom collection of Magento 2:

  1. Create Collection for Pager:
    protected $categorycollectionFactory;
     public function __construct(\Magecomp\Blog\Model\ResourceModel\Category\CollectionFactory $categorycollectionFactory) 
        { 
            $this->categorycollectionFactory = $categorycollectionFactory; 
        }
     public function getCategory()
        {
          //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;
            $categorycollection = $this->categorycollectionFactory->create();
            $categorycollection->setPageSize($pageSize);
            $categorycollection->setCurPage($page);
            return $categorycollection;
        }
    
  2. Add Collection to Pager and Set Available Limits:
    Below code will add pager to layout and set limit for number of items to be shown on each page. This limit setting is totally depends on your requirements, but I would suggest to keep this limit lower in order to avoid effect of it on page load speed. This limit can be set based on size of content like for image, it should be 5 to 10 and for simple list with content, you can set upto 15. Setting limit for Magento 2 pagination is a bit tricky as the speed of default Magento 2 is really slow.
    protected function _prepareLayout()
     {
         parent::_prepareLayout();
         $this->pageConfig->getTitle()->set(__('Categories'));
         if ($this->getNews()) {
             $pager = $this->getLayout()->createBlock(
                'Magento\Theme\Block\Html\Pager',
                'magecomp.category.pager'
             )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection(
                $this->getCategory()
             );
             $this->setChild('pager', $pager);
             $this->getCategory()->load();
         }
         return $this;
     }
    
  3. Getting the Child Block of the Pager:
    This function will return block with pagination and limit items to be shown.
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
    
  4. Add the following Code in phtml File to Call the Pager:

     

Hope this tutorial has helped you to add pagination in custom collection of Magento 2. Let me know if you require more help or any query regarding this. I would appreciate feedback and suggestions for this blog. Till then, Happy Coding!

Click to rate this post!
[Total: 15 Average: 4]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • Hiii
    I don't understand that what can i write with '$pager = $this->getLayout()->createBlock(
    'Magento\Theme\Block\Html\Pager',
    'magecomp.category.pager'' in block file and what should i write in 'magecomp.category.pager' ?

    • magecomp.category.pager
      here
      magecomp -> module root name
      category->module name
      pager->this is from magento default

      • pager will provide
        1) total count and item count for current view . example : Items 7 to 12 of 16 total
        2) pagination
        3) how many you want to show per page like: 5 items per page ,10 items per page, 15 items per page

  • Hiii
    I don't understand that what can i write with '$pager = $this->getLayout()->createBlock(
    'MagentoThemeBlockHtmlPager',
    'magecomp.category.pager'' in block file and what should i write in 'magecomp.category.pager' ?

Recent Posts

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 hours ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

2 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

2 days ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

3 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

5 days ago

HYVÄ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We have brought exciting news for Magento store owners. Hyvä Themes recently released 1.3.6 and…

5 days ago