Magento 2 – Add Pagination to Custom Collection

magento2pagination

I have followed this link to show «per page» limiter on frontend. I have done so far is:

My Collection:

public function getInvoicesCus()
{

    //get values of current page
    $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
     //get values of current limit
    $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;

    $orderCollection = $this->_orderCollectionFactory->create()->addAttributeToSelect('*');
    $orderCollection->addAttributeToFilter('customer_id',$this->getCustomerId());
    $orderCollection->setPageSize($pageSize);
    $orderCollection->setCurPage($page);
    $orderCollection->load();
    //echo "<pre>";

    $invoices_data = array();
    foreach($orderCollection as $orderData)
    {
        $order_id = '';
        $order_id = $orderData->getData('increment_id');

        foreach ($orderData->getInvoiceCollection() as $invoice)
        {
            $invoices_all_data = $invoice->getData();
            $invoices_data[] = $invoices_all_data;
        }
    }
    return $invoices_data;
}

Added Collection to Pager as:

protected function _prepareLayout()
{
    parent::_prepareLayout();
    $this->pageConfig->getTitle()->set(__('Invioices'));
    if ($this->getInvoicesCus()) {
        $pager = $this->getLayout()->createBlock(
        'Magento\Theme\Block\Html\Pager',
        'magecomp.category.pager'
        )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection(
        $this->getInvoicesCus()
        );
        $this->setChild('pager', $pager);
        $this->getInvoicesCus()->load();
    }
    return $this;
} 

Getting the Child Block of the Pager as:

public function getPagerHtml()
{
return $this->getChildHtml('pager');
}

and to call the pager in phtml:

<?php if ($block->getPagerHtml()): ?>
    <div class="order-products-toolbar toolbar bottom"><?= $block->getPagerHtml() ?></div>
<?php endif ?>
<?php else: ?>
    <div class="message info empty"><span><?= /* @escapeNotVerified */ __('You have placed no orders.') ?></span></div>
<?php endif ?>

But when I am always getting this messege in output:

"You have placed no orders."

Can anybody spot the issue ? Thanks

N.B : I am getting order invoices as output if comment pagination code.

Best Answer

Not sure. But, just remove load() from _prepareLayout()

protected function _prepareLayout()
{
    parent::_prepareLayout();
    $this->pageConfig->getTitle()->set(__('Invioices'));
    if ($this->getInvoicesCus()) {
        $pager = $this->getLayout()->createBlock(
        'Magento\Theme\Block\Html\Pager',
        'magecomp.category.pager'
        )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection(
        $this->getInvoicesCus()
        );
        $this->setChild('pager', $pager);
        $this->getInvoicesCus();
    }
    return $this;
} 
Related Topic