Pagination in CodeIgniter: fixing the variable number of displayed links

There was one little thing in the CodeIgniter v2.1.3 built in Pagination library which made me a little confused. In short, the library renders the variable number of links if current page is one of the first or last ones. Let me illustrate it:

     1 2 3 next
prev 4 5 6 7 8 next
prev 7 8 9

The above example shows how the pagination links are rendered with 9 total pages in three cases: when current page number is somewhere in the beginning, in the middle, and in the end, with the parameter $config['num_links'] equal to 2.

So what's wrong here? Actually, here is nothing wrong, except of the fact that I prefer to expect following result:

     1 2 3 4 5 next
prev 4 5 6 7 8 next
prev 5 6 7 8 9

I.e. I want the number of links to be always constant when it possible, regardless to the position of the current page. If current page is somewhere in beginning, then the missing amount of links should be added to the end, and vice versa.

The Pagination library has parameter $config['num_links'] which controls the number of links displayed before and after the current page number. But, unfortunately for me, there is no parameter which would allow me to get result illustrated above, so I had to override the Pagination class.

First, I copied Pagination.php file from system/libraries directory to application/libraries. Now CodeIgniter will use that file for rendering pagination instead of system one, so there will be no any modifications done inside the core files.

Next, inside of the copied Pagination.php I found the piece of code which calculates the numbers of the first and last displayed links. It starts on line 208:

// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0)
       ? $this->cur_page - ($this->num_links - 1) : 1;
$end   = (($this->cur_page + $this->num_links) < $num_pages)
       ? $this->cur_page + $this->num_links : $num_pages;

So right here is a great place to write the custom code for a little correction of the calculated numbers. Here is my addition which I wrote directly after the above chunk:

if ($this->constant_num_links)
    if ($start == 1)
        $end += $this->num_links - $this->cur_page + 1;
        if ($end > $num_pages)
            $end = $num_pages;
    if ($end == $num_pages)
        $start -= $this->num_links - ($num_pages - $this->cur_page);
        if ($start < 1)
            $start = 1;

At the line 62, I added parameter which would allow me to switch the new functionality on and off:

var $constant_num_links = FALSE;

And here we go. To activate new behaviour, Pagination class should be initialized with parameter $config['constant_num_links'] = TRUE.

By on
If you want to repost this article, please keep the source hyperlink