PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 5, 2022

[FIXED] CakePHP outputting redundant pagination link on last page

 January 05, 2022     cakephp, cakephp-3.0, pagination     No comments   

Issue

I'm using a custom pagination template with CakePHP 3.7

The template is in config/infinite-scroll-paginator.php. I want to use this with the Infinite Scroll jquery plugin. Therefore all that's required is 1 link per paginated page which contains the URL to the "next" page (i.e. next set of results).

So in the file above I have:

$config = [
    'nextActive' => '<a class="pagination__next" aria-label="Next" href="{{url}}">{{text}}</a>'
];

In my Controller I start by telling it to use the custom pagination template:

public $helpers = [
    'Paginator' => ['templates' => 'infinite-scroll-paginator']
];

Then when I want to paginate my data I use a custom finder (findFilters() which is in Model/Table/FiltersTable.php):

public $paginate = [
    'finder' => 'filters',
];

I can then use this to get paginated data:

$this->loadModel('Filters');
$rf_keywords = trim($this->request->getQuery('rf_keywords'));

// Pagination
$page = $this->request->getQuery('page') ? (int)$this->request->getQuery('page') : 1;
$this->paginate = ['page' => $page, 'limit' => 100];

$finder = $this
    ->Filters
    ->find('filters', [
        'rf_keywords' => $rf_keywords
    ]);

$data = $this->paginate($finder);
$this->set('data', $data);

Then in my template I output the paginator HTML:

<?= $this->Paginator->next(); ?>

All of this works fine. I get a "next" link for each page. Say if I have 10 pages I get URL's:

/get-filters/?page=1
/get-filters/?page=2
...
/get-filters/?page=10

The issue is that on the 10th page there is a "next" link and the URL of it is just

/get-filters

There are no more pages to output but I still get a link, albeit an invalid one.

How can I stop it from outputting the link on the last page? I thought that the paginator component would take care of this since it's aware how many pages there are based on my limit value in $this->paginate?


Solution

Use $this->Paginator->hasNext() which returns true or false depending on whether there is a "next page".

In the template:

<?php if ($this->Paginator->hasNext()): ?>
<?= $this->Paginator->next(); ?>
<?php endif; ?>


Answered By - Andy
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing