{"id":159,"date":"2018-08-22T12:15:24","date_gmt":"2018-08-22T12:15:24","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2018\/08\/22\/add-pagination-in-magento-2-custom-collection\/"},"modified":"2025-05-22T17:23:30","modified_gmt":"2025-05-22T11:53:30","slug":"add-pagination-in-magento-2-custom-collection","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/add-pagination-in-magento-2-custom-collection\/","title":{"rendered":"How to Add Pagination in Magento 2 Custom Collection"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Pagination&nbsp;divides content into separate pages to prevent your pages from becoming too long and overwhelming. It also helps to improve the user experience by showing the smaller chunk of information so that the users can focus on important parts of the page with reduced scrolling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Magento 2, by default, provides the pagination facility for the product pages, category pages, etc. 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 degrade the SEO!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The default Magento 2 does not provide pagination for a custom collection. To&nbsp;add pagination in&nbsp;Magento 2&nbsp;custom&nbsp;collection<em><strong>,<\/strong><\/em>&nbsp;follow below steps and you\u2019ll get the desired output.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to Add Pagination in Magento 2 Custom Collection<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Create Controller File at&nbsp;Vendor\\Extension\\Controller\\Index\\Index.php<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\Extension\\Controller\\Index;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Magento\\Framework\\App\\Action\\Action;\nclass Index extends Action\n{\n    protected $resultPageFactory;\n    \n    public function __construct(\n        Context $context,\n        PageFactory $resultPageFactory\n    ) {\n    \n        parent::__construct($context);\n        $this->resultPageFactory = $resultPageFactory;\n    }\n    public function execute()\n    {\n        $resultPage = $this->resultPageFactory->create();\n        $resultPage->getConfig()->getTitle()->set(__('Custom Pagination'));\n        return $resultPage;\n    }\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Create block file at&nbsp;Vendor\\Extension\\Block\\Index.php<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\Extension\\Block;\nuse Magento\\Framework\\View\\Element\\Template;\nuse Magento\\Framework\\View\\Element\\Template\\Context;\nuse Vendor\\Extension\\Model\\Extension;\nuse Magento\\Framework\\Pricing\\Helper\\Data as priceHelper;\nclass Index extends Template\n{\n    protected $customCollection;\n    protected $priceHepler;\n    public function __construct(Context $context, Extension $customCollection,priceHelper $priceHepler)\n    {\n        $this->customCollection = $customCollection;\n        $this->priceHepler = $priceHepler;\n        parent::__construct($context);\n    }\n    protected function _prepareLayout()\n    {\n        parent::_prepareLayout();\n        $this->pageConfig->getTitle()->set(__('Custom Pagination'));\n        if ($this->getCustomCollection()) {\n            $pager = $this->getLayout()->createBlock(\n                'Magento\\Theme\\Block\\Html\\Pager',\n                'custom.history.pager'\n            )->setAvailableLimit([5 => 5, 10 => 10, 15 => 15, 20 => 20])\n                ->setShowPerPage(true)->setCollection(\n                    $this->getCustomCollection()\n                );\n            $this->setChild('pager', $pager);\n            $this->getCustomCollection()->load();\n        }\n        return $this;\n    }\n    public function getPagerHtml()\n    {\n        return $this->getChildHtml('pager');\n    }\n    public function getCustomCollection()\n    {\n        $page = ($this->getRequest()->getParam('p')) ? $this->getRequest()->getParam('p') : 1;\n        $pageSize = ($this->getRequest()->getParam('limit')) ? $this->getRequest(\n            \n        )->getParam('limit') : 5;\n        $collection = $this->customCollection->getCollection();\n        $collection->setPageSize($pageSize);\n        $collection->setCurPage($page);\n        return $collection;\n    }\n    public function getFormattedPrice($price)\n    {\n        return $this->priceHepler->currency(number_format($price, 2), true, false);\n    }\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.Create layout file at&nbsp;Vendor\\Extension\\view\\frontend\\layout\\extension_index_index.xml<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;page xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/..\/..\/..\/..\/lib\/internal\/Magento\/Framework\/View\/Layout\/etc\/page_configuration.xsd\">\n    &lt;body>\n        &lt;referenceContainer name=\"columns.top\">\n            &lt;block class=\"Magento\\Theme\\Block\\Html\\Title\" name=\"page.main.title\" template=\"html\/title.phtml\"\/>\n            &lt;container name=\"page.messages\" htmlTag=\"div\" htmlClass=\"page messages\">\n                &lt;block class=\"Magento\\Framework\\View\\Element\\Template\" name=\"ajax.message.placeholder\" template=\"Magento_Theme::html\/messages.phtml\"\/>\n                &lt;block class=\"Magento\\Framework\\View\\Element\\Messages\" name=\"messages\" as=\"messages\" template=\"Magento_Theme::messages.phtml\"\/>\n            &lt;\/container>\n        &lt;\/referenceContainer>\n        &lt;referenceBlock name=\"page.main.title\">\n            &lt;action method=\"setPageTitle\">\n                &lt;argument translate=\"true\" name=\"title\" xsi:type=\"string\">Custom Pagination&lt;\/argument>\n            &lt;\/action>\n        &lt;\/referenceBlock>\n        &lt;referenceContainer name=\"content\">\n            &lt;block class=\"Vendor\\Extension\\Block\\Index\" name=\"ecustom_pagination\" template=\"Vendor_Extension::index.phtml\"  cacheable=\"false\" >\n            &lt;\/block>\n        &lt;\/referenceContainer>\n    &lt;\/body>\n&lt;\/page><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Create template file at&nbsp;Vendor\\Extension\\view\\frontend\\templates\\index.phtml<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php if ($block->getPagerHtml()): ?>\n    &lt;div class=\"order-products-toolbar toolbar bottom\">&lt;?php echo $block->getPagerHtml(); ?>&lt;\/div>\n&lt;?php endif ?>\n&lt;?php $gridrecords = $block->getCustomCollection(); ?>\n&lt;?php if ($gridrecords &amp;&amp; sizeof($gridrecords)): ?>\n    &lt;div class=\"table-wrapper orders-history\">\n        &lt;table class=\"data table table-order-items history\" id=\"my-orders-table\">\n            &lt;caption class=\"table-caption\">&lt;?php echo __('Grid Record') ?>&lt;\/caption>\n            &lt;thead>\n            &lt;tr>\n                &lt;th scope=\"col\" class=\"col id\">&lt;?php echo __('ID') ?>&lt;\/th>\n                &lt;th scope=\"col\" class=\"col title\">&lt;?php echo __('Created At') ?>&lt;\/th>\n                &lt;th scope=\"col\" class=\"col product\">&lt;?php echo __('Product Name') ?>&lt;\/th>\n                &lt;th scope=\"col\" class=\"col amount\">&lt;?php echo __('Price') ?>&lt;\/th>\n            &lt;\/tr>\n            &lt;\/thead>\n            &lt;tbody>\n            &lt;?php\n            foreach ($gridrecords as $gridrecord): ?>\n                &lt;tr>\n                    &lt;td data-th=\"&lt;?= $block->escapeHtml(__('ID')) ?>\" class=\"col id\">\n                        &lt;?php echo $gridrecord->getId() ?>\n                    &lt;\/td>\n                    &lt;td data-th=\"&lt;?= $block->escapeHtml(__('Created At')) ?>\"\n                        class=\"col title\">&lt;?php echo date('Y-m-d', strtotime($gridrecord->getCreatedDate())); ?>&lt;\/td>\n                    &lt;td data-th=\"&lt;?= $block->escapeHtml(__('Product Name')) ?>\" class=\"col product\">\n                            &lt;?php echo $gridrecord->getProductName() ?>\n                    &lt;\/td>\n                    &lt;td data-th=\"&lt;?= $block->escapeHtml(__('Price')) ?>\"\n                        class=\"col amount\">&lt;?php echo $block->getFormattedPrice($gridrecord->getPrice()) ?>&lt;\/td>\n                &lt;\/tr>\n            &lt;?php endforeach; ?>\n            &lt;\/tbody>\n        &lt;\/table>\n    &lt;\/div>\n    &lt;?php if ($block->getPagerHtml()): ?>\n        &lt;div class=\"order-products-toolbar toolbar bottom\">&lt;?php echo $block->getPagerHtml(); ?>&lt;\/div>\n    &lt;?php endif ?>\n&lt;?php else: ?>\n    &lt;div class=\"message info empty\">&lt;span>&lt;?php echo __('No any record.'); ?>&lt;\/span>&lt;\/div>\n&lt;?php endif ?><\/pre>\n\n\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2018\/08\/pagintion-output.png\" alt=\"pagination output after adding pagination in Magento 2\" class=\"wp-image-3350\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The grid created by the above implementation will be responsive! Hope this blog has served your purpose to implement pagination.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When adding pagination to a custom collection in Magento 2, it&#8217;s essential to control the number of items displayed per page. One effective way to achieve this is by using the <a href=\"https:\/\/meetanshi.com\/blog\/how-to-use-setpagesize-in-magento-2-collections\/\"><code>setPageSize<\/code> method<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank You!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Pagination&nbsp;divides content into separate pages to prevent your pages from becoming too long and overwhelming. It also helps to improve the user experience by showing&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-159","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/159","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=159"}],"version-history":[{"count":6,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/159\/revisions"}],"predecessor-version":[{"id":15618,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/159\/revisions\/15618"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=159"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=159"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=159"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}