4

I have added an ajax pagination in a custom module collection. I have a total of 50 items in the collection and the limit per page is 5; that should show total page of 10.

Instead, it is showing only 5 pages, it is not showing the next page Link either and there is no active clickable page link.

When I click on 5 (number page) or Next arrow should display next page like 6 7 8 etc but it does not

I have followed the File path Below to implement This pagination.

Step 1: Block file code.

File path: app/code/Vendor/Module/Block/Test.php

public function getPagerHtml()
{
    if ($this->getLayout()->getBlock('test.page.pager')) {
        $this->pager = $this->getLayout()->getBlock('test.page.pager');

        return $this->pager->toHtml();
    }

    if (!$this->pager) {
        $this->pager = $this->getLayout()->createBlock(
            Pager::class,
            'test.page.pager'
        );

        if ($this->pager) {
            $this->pager->setUseContainer(
                false
            )->setShowPerPage(
                false
            )->setShowAmounts(
                false
            )->setFrameLength(
                $this->_scopeConfig->getValue(
                    'design/pagination/pagination_frame',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                )
            )->setJump(
                $this->_scopeConfig->getValue(
                    'design/pagination/pagination_frame_skip',
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                )
            )->setLimit(5)->setCollection(
                $this->getLocationCollection()
            );

            return $this->pager->toHtml();
        }
    }

    return '';
}

public function getLocationCollection()
{
    $pageNumber = (int)$this->getRequest()->getParam('p') ? (int)$this->getRequest()->getParam('p') : 1;
    if (!$this->itemCollection) {
        $this->itemCollection = $this->itemCollectionFactory->create();
    }
    $this->itemCollection->setCurPage($pageNumber);
    $this->itemCollection->setPageSize(5);

    return $this->itemCollection;
}

protected function _prepareLayout()
{     
      
    $this->getPagerHtml();

    if ($this->pager && !$this->pager->isFirstPage()) {
        $this->addPrevNext(
            $this->getUrl('testpage/index/ajax', ['p' => $this->pager->getCurrentPage() - 1]),
            ['rel' => 'prev']
        );
    }

    if ($this->pager && $this->pager->getCurrentPage() < $this->pager->getLastPageNum()) {
        $this->addPrevNext(
            $this->getUrl('testpage/index/ajax', ['p' => $this->pager->getCurrentPage() + 1]),
            ['rel' => 'next']
        );
    }    

    return parent::_prepareLayout();
}

 /**
 * Add prev/next pages
 *
 * @param string $url
 * @param array $attributes
 *
 */
private function addPrevNext($url, $attributes)
{
    $this->pageConfig->addRemotePageAsset(
        $url,
        'link_rel',
        ['attributes' => $attributes]
    );
}

Step 2: Controller file.

File path: app/code/Vendor/Module/Controller/Index/Ajax.php

public function execute()
{
    $params = $this->getRequest()->getParams();
    $storeId = $this->storeManager->getStore()->getId();

    if(isset($params['pageNo'])){
        $pageNo = $params['pageNo'];
    }else{
        $pageNo = 1;
    }

    $collection = $this->collectionFactory->create()
                ->addFieldToFilter('is_active', 1)
                ->addStoreFilter($storeId)
                ->setPageSize(5) 
                ->setCurPage($pageNo); 

    $data = $this->prepareData($collection->getData());
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($data);
    return $resultJson;
}

Step 3: Template file.

File path: app/code/Vendor/Module/view/frontend/templates/pagetest.phtml

<?php  if ($pager = $block->getPagerHtml()): ?>
    <div class="testpage-pager-container"><?= /** @escapeNotVerified */ $pager; ?></div>
<?php endif;  ?>

Step 4: JS file code.

File path: app/code/Vendor/Module/view/frontend/web/js/testpage.js

$(".testpage-pager-container li a").live('click', function(event) {
    event.preventDefault();

    var pagignationUrl= $(this).attr('href'); 
    var pageSplit = pagignationUrl.split('/');
    var pageNo = pageSplit[pageSplit.length - 2];  
    $.ajax({
        url : self.options.ajaxUrl,
        type: self.options.method,
        dataType: 'json',
        data: {pageNo: pageNo},
        showLoader: true,
        beforeSend: function() {
        },
        success : function(res) {  
           $('#items-list').html(res);
        },
        error : function(request,error)
        {
            alert("Error");
        }
    });    
});

enter image description here

Any help would be appreciated. Thanks.

17
  • The problem seems to be in your block "app/code/Vendor/Module/Block/Test.php", please debug that carefully. For example, the code "->setLimit(5)" in function getPagerHtml should be restricting pagination to 5 – Ravinder Jul 9 '20 at 10:21
  • It is much easier to do an ajax call to your current url with parameters &p={{desired page number}}&current_categoryid={{current category id}} and replace your container of the whole product list with the product list container in the response. – CompactCode Jul 9 '20 at 10:38
  • @Ravinder First of all I appreciate your help. I have checked as per your suggestion in the block to change ->setLimit(10) but not works. – Kirti Nariya Jul 9 '20 at 11:09
  • @CompactCode I have pass the the url and pageNo in ajax call and replace html as well. I have issue in when store have 55 records and limit is 5 then page will 11 and first is showing 1 2 3 4 5 page after click on 5 number of page then it there should be displacy next page like 6 7 8 But not display 6 7 8 page. – Kirti Nariya Jul 9 '20 at 11:12
  • @KirtiNariya in that case, you need to debug the call $this->pager->toHtml(). Debugging it down will let you know why this only prints 5 pagination – Ravinder Jul 9 '20 at 11:56
0

Hi try this once and let know the result

public function execute()
    {
        $params = $this->getRequest()->getParams();
        $storeId = $this->storeManager->getStore()->getId();
    
        if(isset($params['pageNo'])){
            $pageNo = $params['pageNo'];
        }else{
            $pageNo = 1;
        }
    
        $collection = $this->collectionFactory->create()
                    ->addFieldToFilter('is_active', 1)
                    ->addStoreFilter($storeId)
                    ->setPageSize(5) 
                    ->setCurPage(1); 
    
        $data = $this->prepareData($collection->getData());
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($data);
        return $resultJson;
    }
5
  • Thankyou @Chikku but not working. I have checked in console there is no any error. – Kirti Nariya Jul 15 '20 at 6:18
  • still getting same pagination? – Pramod Jul 15 '20 at 6:19
  • Yes. still getting the same pagination and same issue occurs. – Kirti Nariya Jul 15 '20 at 6:27
  • am trying it on my local and will update the ans here if i got success – Pramod Jul 15 '20 at 6:28
  • i think this line ->setCurPage(1); is not taking any effect because you have called $pageNo in this – Pramod Jul 15 '20 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.