I have added one grid in customer account and getting collection also.But when I want to add pager in that grid, that time I am getting an error like :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'main_table.attribute_id' in 'field list', query was: SELECT COUNT(DISTINCT main_table.attribute_id) FROM
custommodule_test
ASmain_table
WHERE (customer_id='2') {"is_exception":false} []
Actually there is not any attribute_id filed is there in my table nor I am filtering for that filed name as you are seeing.
Please have a look :
test.phtml
<?php if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif; ?>
block/test.php
protected function _prepareLayout()
{
parent::_prepareLayout();
if ($this->getCollection()) {
$pager = $this->getLayout()->createBlock(
'Magento\Theme\Block\Html\Pager',
'custom.collection.test'
)->setCollection(
$this->getCollection()
);
$this->setChild('pager', $pager);
$this->getCollection()->load();
}
return $this;
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
public function getCollection()
{
if (!$this->getData('collection')) {
$this->setCollection(
$this->_objectMangaer->get('Namespace\Modulename\Model\Test')->getCollection()->addFieldToFilter('customer_id',2)
);
}
return $this->getData('collection');
}
Please note : If I directly call
$this->getCollection() ;
from phtml file then I got an correct collection.
Best Answer
To fulfil the requirement, we have gone through many approaches and found the best solution for pagination on Magento2 custom collection. Here we are going to explain the best approach please follow the steps.
Note: Assuming that You have created a basic module in Magento2. Here Ipragmatech is our package and Ipreward is our module. Please, change your class name accordingly.
Step 1: Create a controller named Myrewad, action Index (Myreward/Index.php)and add the following code to execute method
Step 2: Create a block (Assuming that you have already created a model for your table. Here We have custom table and we have created the model as reward) name Reward.php and add the following code. In this code, we have added the pager in our custom collection.
} Step 3: Added/Modify the following code on layout file app/code/Ipragmatech/Ipreward/view/frontend/layout/ipreward_myreward_index.xml
Step 4: Add your phtml file as app/code/Ipragmatech/Ipreward/view/frontend/templates/myreward/reward.phtml and add the following code
and the output will be look like this
Sometimes we have faced some CSS issue in which page limit not displayed so use the following CSS if you have the same issue.
Hope this will help you a lot. Please let us know if you have any issue regarding Magento customization.