By default, Magento 2 provides the pagination facility for the product pages, category pages, etc. It helps in easy navigation. Without pagination, the page load time increases.
The default Magento 2 does not provide pagination for a custom collection.
To add pagination in Magento 2 with a custom collection
create a block file in your module :
<?php
namespace MagemonkeyGeneralBlock;
class Monthlyspecial extends MagentoFrameworkViewElementTemplate {
private $_objectManager;
public function __construct(MagentoCatalogBlockProductContext $context,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoFrameworkObjectManagerInterface $objectmanager,
array $data = []) {
parent::__construct($context, $data);
$this->_isScopePrivate = true;
$this->_objectManager = $objectmanager;
$this->scopeConfig = $scopeConfig;
}
protected function _prepareLayout()
{
parent::_prepareLayout();
if ($this->getMonthlySpecial()) {
$pager = $this->getLayout()->createBlock(
'MagentoThemeBlockHtmlPager',
'monthlyspecial.history.pager'
)->setAvailableLimit(array(12=>12,24=>24,36=>36,48=>48,52=>52))
->setShowPerPage(true)->setCollection(
$this->getMonthlySpecial()
);
$this->setChild('pager', $pager);
$this->getMonthlySpecial()->load();
}
return $this;
//return parent::_prepareLayout();
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
Public function getMonthlySpecial()
{
$page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest
()->getParam('limit') : 12;
$cateinstance = $this->_objectManager->create('MagentoCatalogModelCategoryFactory');
$allproduct = $cateinstance->create()->load(0)->getProductCollection()->addAttributeToSelect('*')
->addAttributeToFilter('manager_special', 0)
->addAttributeToFilter('email_special', 0)
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->setOrder('price', 'ASC');
$collection = $allproduct;
$collection->setPageSize($pageSize);
$collection->setCurPage($page);
return $collection;
}
}
create a view phtml file where you use pagination in your module
Just call getPagerHTML() code as per shown below.
<?php echo $this->getPagerHtml() ?>
<?php
$allproduct = $this->getMonthlySpecial();
<div id="layer-product-list">
<div class="toolbar toolbar-products">
<div class="pages">
<?php echo $this->getPagerHtml() ?>
</div>
</div>
<div class="category-products products wrapper grid products-grid">
<?php foreach ($allproduct as $key => $productdata) {
//add code for your data in loop
}
?>
</div>
</div>

