Pagination

By Andy Dawson (AD7six)
If you have more than a few results it is useful, if not vital, to provide a means of presenting the results a few at a time.
This tutorial will demonstrate how easy it is to present your data using pagination.
If part of your application includes displaying lots of results, it's a good idea to give the user the possibility to view the results in digestable chunks and possibly to be able to sort the presented data. This tutorial will explain how, after copying a few files into your application, you can achieve this in very few lines of code.
You need almost no knowledge of cake to be able to make use of this tutorial :).

If you already have a table in mind that you want to add pagination to, read on; otherwise run through http://manual.cakephp.org/appendix/blog_tutorial to have some code to play with.

Setting Up


All of the files necessary are available here in the bakery.

Save this file http://bakery.cakephp.org/articles/view/67 as /app/controllers/components/pagination.php

Save this file http://bakery.cakephp.org/articles/view/68 as /app/views/helpers/pagination.php

Save this file http://bakery.cakephp.org/articles/view/69 as /app/views/elements/pagination.thtml

Create/modify the Controller


The only change necessary to use pagination is to include the component, the helper and call the component method "init" before the relavent find.

Controller Class:

Download code <?php 
class PostsController extends AppController
{
    var 
$name 'Posts'// for PHP4 installs
    
var $components = array ('Pagination'); // Added
    
var $helpers = array('Pagination'); // Added

    
function index() {    
        
$criteria=NULL;
        list(
$order,$limit,$page) = $this->Pagination->init($criteria); // Added
        
$data $this->Post->findAll($criteriaNULL$order$limit$page); // Extra parameters added
        
        
$this->set('data',$data);
    }
}
?>

Create/modify the View


To make use of pagination, include the element, and optionally modify your table headers to allow changing the sort order of results:

View Template:

Download code
<h1>Paginated Posts Index</h1>
<table>
<?php
$pagination
->setPaging($paging); // Initialize the pagination variables
$th = array (
            
$pagination->sortBy('id'),
            
$pagination->sortBy('title'),
            
$pagination->sortBy('created')
); 
// Generate the pagination sort links
echo $html->tableHeaders($th); // Create the table headers with sort links if desired

foreach ($data as $output)
{
    
$tr = array (
        
$output['Post']['id'],
        
$html->link($output['Post']['title'], "/Posts/View/{$output['Post']['id']}"),
        
$output['Post']['created']
        );
    echo 
$html->tableCells($tr,array('class'=>'altRow'),array('class'=>'evenRow'));
}
?>
</table>
<? echo $this->renderElement('pagination'); // Render the pagination element ?>


Adding Ajax updates


If you include the RequestHandler component, the AJAX helper in your controller and the prototype js file is loaded in your view - you get your updates by ajax. Yes, it's that simple. The div that will be updated by default is the "content" div, you can change this by specifying in the component (either directly, or at run time) which div to update. And yes, you can disable this automatic behaviour if required.

How to add Prototype


So how do you add the prototype library..? Well...
Modify your layout

The Prototype JavaScript library is availble at http://prototype.conio.net/
put prototype.js in /app/webroot/js/
Add the JavaScript code inside the <head> tag

PHP Snippet:

Download code <?php 
if(isset($javascript)):
    echo 
$javascript->link('prototype.js');
endif;          
?>

Page 2: Additional info

Comments 65

CakePHP Team Comments Author Comments
 

Comment

1 GET string creation

Hello,

great code and a nice tutorial, thanks for sharing it!

I'm not sure if you can consider this a bug, but I was getting html validation errors because of "&" in the get string (like in: "/users/index?sortBy=email&page=2".

I've changed the line 550 in the helper
$getString = implode ("&", $getString);

to this:
$getString = implode ("&amp;amp;", $getString);

and it was ok.

regards, danielz
Posted Oct 11, 2006 by DanielZ
 

Comment

2 modelClass attribute

Hi, thanks for this great component. I had some difficulties when requesting data from another model than the controller's default.
I have worked around it by setting the attribute $this->Pagination->modelClass to the Model name I wanted to use. I think that it should be then a public attribute, or maybe rethink the component to accept different Model names for Default sortBy condition and for counting the elements returned by the criteria would be a nice enhancement.
Posted Oct 12, 2006 by Jose Lorenzo Rodriguez
 

Comment

3 modelClass attribute

I had some difficulties when requesting data from another model than the controller's default.
I have worked around it by setting the attribute $this->Pagination->modelClass to the Model name I wanted to use. I think that it should be then a public attribute, or maybe rethink the component to accept different Model names for Default sortBy condition and for counting the elements returned by the criteria would be a nice enhancement.


This already is a public attribute. Just pass the key 'sortByClass' with your Modelname as the value in the third options array for init(). For example:

$this->Pagination->init(null,null, array('sortByClass'=>'Foo','sortBy'=>'bar'));

Posted Oct 13, 2006 by Jean-Claude Siegrist
 

Question

4 Unclear error

But what if the controller is for more than one models and it's not called as model itself. In my case I have one admincontroller and when I try to initalize pagination I get this error.

<code>Notice: Undefined property: AdminController::$Admin in C:\apache2triad\htdocs\cake_plugin\app\controllers\components\pagination.php on line 212 Fatal error: Call to a member function findCount() on a non-object in C:\apache2triad\htdocs\cake_plugin\app\controllers\components\pagination.php on line 212</code>
Posted Oct 16, 2006 by Peco Danajlovski
 

Comment

5 Reply

Hi all,

I have worked around it by setting the attribute $this->Pagination->modelClass ...
Following up on what Jean-Claude Siegrist has said, that's not really necessary. For any field you can override what is in the component by passing info in the 3rd paramter. For this example $this->Pagination->init(null,null,array('modelClass'=>'otherModel'));

Regarding the admin error, and bypassing commenting on the use of admin routes, this can also be solved in the same way. Although I am not sure how that error occurs as by default the component uses the controller modelClass (have you set your controller $uses var to null?).
Posted Oct 16, 2006 by Andy Dawson
 

Question

6 Keeping the search criteria from page to page

Using the pagination component, you have initial control over the criteria you give to it (from a search page typically), as in:

list($order, $limit, $page) = $this->Pagination->init($criteria);

However, when you render the pagination element, you seem to have no control anymore on the criteria. With the following rendering, shifting to another page (or asking for a different page size) makes you loose your filtering:

$this->renderElement("pagination");

Is there a technique to make the criteria available consistently through the page and page siez links ?

Posted Oct 23, 2006 by Iharizaka Rahaingoson
 

Comment

7 Great Component

Thanks man I really like the way this component works. Simple and easy.
Posted Oct 23, 2006 by Carlos Mauricio Samour
 

Question

8 Sorting by associated attributes

Great component, thanks!

Quick question - if you have a table based on a particular model and you want to display sortable columns where sortable them take data from another (associated) model, how is this done? In the tutorial above for example, how would you add a sortable column that shows the post's author name?

I've tried switching the model via the 3rd parameter of $pagination->sortBy but that didn't seem to work instead throwing 'SQL Error in model: Unknown column'. Any suggestions?

Posted Oct 26, 2006 by Andrew Jessup
 

Comment

9 Reply

Hi all,

I'd recommend the link "Page 2: Additional info" if the first page doesn't satisfy your thirst for knowledge :).

Iharizaka Rahaingoson:
There are 2 main ways of handling searches
1) Process the form and redirect the user to a page with the constraint in the url
2) 'Pull' the search form info with each pagination link (requires Ajax).

I would recommend the first, and I've spoken about it on the google group a few times; there are demos of both from the links of "Page 2: Additional info".

Andrew Jessup:
Also on "Page 2: Additional info" you'll see a description of each of the parameters. To change the model used in the sort you would specify sortByClass. Be aware that the pagination component simply feeds info back for you to use in your subsequent findAll - if it's not possible to sort the results by the class that you specify (if the association for the class you specify is not hasOne or belongsTo the primary search won't contain the class), you'll get error messages and/or no results.

Anyway, HTH
Posted Oct 26, 2006 by Andy Dawson
 

Comment

10 Pagination rocks

Thanks Andy for devoting your time to this, pagination is awesome ; ).
Posted Oct 27, 2006 by Felix Geisendoerfer
 

Question

11 sortBy not having any effect

To my understanding sortBy is used to set the default sort order, if I am not wrong it will set the ORDER BY value for the generated sql statement.

I have tried bothe the approch


$this->Pagination->direction = 'ASC';
$this->Pagination->sortBy = 'created';
list($order,$limit,$page) = $this->Pagination->init($criteria);

~~~AND~~~

list($order,$limit,$page) = $this->Pagination->init($criteria,null,array('sortBy' => 'created', 'direction' => 'DESC'));

In both the cases when I am changing the value of direction its working properly but the sortBy stuff is not working. Even I change the value of

/**
* Specify DEFAULT sort column.
*
* @var string
* @access public
*/
var $sortBy = 'id';

to

var $sortBy = 'created';

the generated SQL is still showing

...ORDER BY `Event`.`id`...

Am I doing something wrong. I have read both the articles several time .. Am I missing something? Your help is highly appreciated and I am thankful to you for this component. If you can please help me to solve the issue , that will be very nice.

* Please forgive me for my bad English :) cheers

suman
Posted Oct 31, 2006 by Suman Paul
 

Question

12 Changing limit

Hi, I'm new to all this so I'm having some issues. I did this tutorial with a table that has thousands of records. It all works, but with only 5 results per page I get far too many pages. I went into the controller and changed the line
$data = $this->Post->findAll($criteria, NULL, $order, $limit, $page);
to
$data = $this->Post->findAll($criteria, NULL, $order, 100, $page);

It changed the results page to 100 records but at the bottom is still says "Results: 1-5 of 2373". Where can I change that?
Posted Nov 3, 2006 by Ro
 

Comment

13 set resultsPerPage array

Hi Ro,

I guess you have to set resultsPerPage in the controller
so this :

$this->Pagination->resultsPerPage = array(100,200,500);
$this->Pagination->show = 100;
list($order,$limit,$page) = this->Pagination->init($criteria);

I think that will solve the issue.

cheers
Posted Nov 3, 2006 by Suman Paul
 

Comment

14 Reply

To my understanding sortBy is used to set the default sort order
100% correct, but there was a missing if statement in a previous version of the component which caused the sort field to always be overwritten with the primary key field. Note I say "was" that was corrected on 2006-09-25. If you take the code from the bakery that problem is solved.

[quote}$data = $this->Post->findAll($criteria, NULL, $order, 100, $page);
That will certainlly work, but of course the pagination code won't know that you are overriding the values it's giving you :).
If you want to fix completely the number of results, such that the user can't change them you could do:

PHP Snippet:

<?php 
$settings 
= array (
    
'resultsPerPage' => array(100),
    
'privateParams' = array("show");
);
list(
$order,$limit,$page) = $this->Pagination->init(NULL,NULL,$settings);
?>

The resultsPerPage parameter set's the possibilities that you can choose from, and the privateParams parameter means you can't change it from the web. (Note that: In this example it's not necessary to specify the privateParms, because if you try to show a number of results that are not in the resultsPerPage array - the default value is used.)

If you wanted simply to change the default number of results that are displayed when you first load the page, you could do:

PHP Snippet:

<?php 
$settings 
= array (
    
'show' => 100
);
list(
$order,$limit,$page) = $this->Pagination->init(NULL,NULL,$settings);
?>

Or any other permutation you can think of :). Again, I'd recommend page 2 of this article for the description of parameters and links to the examples which you can download.
Posted Nov 4, 2006 by Andy Dawson
 

Comment

15 It Works

Thanks Andy ...it is working perfectly after the update :)

thank you again very much
Posted Nov 4, 2006 by Suman Paul
 

Question

16 Pretty URLs

Great work! Just 1 small problem. I just can't get the pretty URLs to work.

The URLs output properly, but when I click them it doesn't recognise that i have set a pagination variable.
Posted Nov 21, 2006 by Brett ODonnell
 

Comment

17 Great Job.

Great job on this tutorial, and its accompanying code.
Posted Nov 22, 2006 by Darian Anthony Patrick
 

Comment

18 Pretty Params

Hi Brett,

Pretty (or named) params are something that should be app level rather than pagination specific, hence it doesn't take care of that in the component itself. All you need to do is use something like http://bakery.cakephp.org/articles/view/129 and pass the results in the second parameter to the component init call. If you can't get it working, again, I'd recommend page 2 of this article for the description of parameters and links to the examples which you can download.
Posted Nov 22, 2006 by Andy Dawson
 

Question

19 SortBy

Thanks a lot for such a nice code, But I am facing a problem in it. When i navigate to any page through pagination, and click on the sortable field , it do sorts the records but takes me to the first page and then shows me the sorted records.

As i am new to cakephp , Please can anybody tell me wat shud i do?
Posted Nov 24, 2006 by kashish
 

Question

20 Getting it to work with Ajax

I can't seem to get it to work with Ajax. I have the following in my controller:

var $helpers = array('Html', 'Form' , 'Ajax', 'Javascript', 'Pagination' );
var $components = array( 'Pagination', 'Autocomplete', 'RequestHandler' );

In the controller action, I'm resetting the name of the div:

$this->Pagination->ajaxDivUpdate = 'users';

I have the following in my layout:

<?php
echo $javascript->link( 'prototype.js' );
echo $javascript->link( 'scriptaculous.js' );
?>

I have the following in my view:

<?php
$pagination->setPaging($paging); // Initialize the pagination variables
echo $this->renderElement('pagination'); // Render the pagination element
?>

And this is what the rendered:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>





Users
</head>
<body>
<div class='lefty'> <!--the first outer wrapper that put the left column down -->
<div class='righty'> <!--the first outer wrapper that put the left column down -->

<img src="/narthex/img/border_top_left.gif" id="leftMonk" />
<img src="/narthex/img/border_top_right.gif" id="rightMonk" />
<div class="maincontent">
<div class="users">
<h2>List Users</h2>

<table cellpadding="0" cellspacing="0">
<tr>
<th>Id</th>
<th>Last Login</th>

<th>Name</th>
<th>Email</th>
<th>City</th>
<th>State</th>
<th>Country</th>
<th>Comments</th>

<th>Theme</th>
<th>Onsite Trades</th>
<th>Hide Inventory</th>
<th>Created</th>
<th>Modified</th>

</tr>
<tr>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
</table>
<br /><br /><br />
<div id='pagination'>
Results: 1-5 of 290<br />
<img src="/narthex/img/nav/arrowleft.gif" height="15" alt="previous" />
<em>1</em> |
<a href="/narthex/users/index?page=2" id="link300548541" >2</a>Event.observe('link300548541', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=2', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=3" id="link134229918" >3</a>Event.observe('link134229918', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=3', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=4" id="link636650378" >4</a>Event.observe('link636650378', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=4', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=5" id="link359638782" >5</a>Event.observe('link359638782', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=5', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=6" id="link777065471" >6</a>Event.observe('link777065471', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=6', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=7" id="link821092498" >7</a>Event.observe('link821092498', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=7', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
<a href="/narthex/users/index?page=8" id="link1802514728" >8</a>Event.observe('link1802514728', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=8', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); | ... |
<a href="/narthex/users/index?page=58" id="link1062195278" >58</a>Event.observe('link1062195278', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=58', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); <a href="/narthex/users/index?page=2" id="link1386862443" ><img src="/narthex/img/nav/arrowright.gif" height="15" alt="next" /></a>Event.observe('link1386862443', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=2', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);<br />Results per page: <a href="/narthex/users/index?show=2" id="link301462652" >2</a>Event.observe('link301462652', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=2', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
<em>5</em>
<a href="/narthex/users/index?show=10" id="link2077237105" >10</a>Event.observe('link2077237105', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=10', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
<a href="/narthex/users/index?show=20" id="link1525874046" >20</a>Event.observe('link1525874046', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=20', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
<a href="/narthex/users/index?show=50" id="link325316442" >50</a>Event.observe('link325316442', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=50', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
<a href="/narthex/users/index?show=100" id="link1796660853" >100</a>Event.observe('link1796660853', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=100', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
<a href="/narthex/users/index?show=500" id="link1462213788" >500</a>Event.observe('link1462213788', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=500', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
</div>
</div>
</div>
</div>
</div>
</body>
</html>

As you can see, all the important parts are there. And it looks like all the appropriate javascript/AJAX code is there, too. But whenever I click on any of the links, nothing happens. What am I missing? Do I need to add additional code to the controller somewhere?

thnx,
Christoph
Posted Nov 25, 2006 by Christoph
 

Question

21 Getting it to work with Ajax

The HEAD didn't come through correctly. I guess it got stripped out. Below is what it should have said. I've reversed the symbols so it wouldn't get stripped.

>head<
>meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /<
>link rel="stylesheet" type="text/css" href="/narthex/css/Vtes.css" /<
>link rel="stylesheet" type="text/css" href="/narthex/css/News.css" /<
>script type="text/javascript" src="/narthex/js/prototype.js"<>/script<
>script type="text/javascript" src="/narthex/js/scriptaculous.js"<>/script<
>title<Users>/title<
>/head<
Posted Nov 25, 2006 by Christoph
 

Comment

22 Reply and Ajax

Hi Kasish,

It's not clear to me what you are expecting to happen that is different from what it does - probably best to use the irc channel to find someone to discuss with.

Hi Christoph,

$this->Pagination->ajaxDivUpdate = 'users';

It would be cleaner if you set that directly in the component if it's a generic setting (which in this case it doesn't seem to be) or in the 3rd parameter of the init call rather than setting it directly.

Regarding ajax, the reason it doesn't work is that you don't have a div with the id 'users'. If you correct that, suddenly the magic will happen (assuming your prototype js file is in place).
Posted Nov 26, 2006 by Andy Dawson
 

Question

23 I am having the same Problem

Using the pagination component, you have initial control over the criteria you give to it (from a search page typically), as in:

list($order, $limit, $page) = $this->Pagination->init($criteria);

However, when you render the pagination element, you seem to have no control anymore on the criteria. With the following rendering, shifting to another page (or asking for a different page size) makes you loose your filtering:

$this->renderElement("pagination");

Is there a technique to make the criteria available consistently through the page and page siez links ?



It just, doesn't keep the query through action.

for example if you do a form to construct a sql query to search content, and uses $this->data to do it.

Anyone has a solution for this issue, i would great to this component get the form data an keep it.

pd: excluse my english, regards from Bolivia.
Posted Nov 27, 2006 by Mario Cesar
 

Bug

24 little fix for no mod rewrite

I had trouble using it on an environment with no mod-rewrite. Actually this is handled into the pagiantion component, but I need to add :

if( defined(BASE_URL))
{
....
....

// added this to finish by /

if(substr($this->url, -1, 1)<>"/")
{
$this->url .= "/";
}
}

A part from this, everything works great. I am amending it to store the previous value into the Session in order to be able to "come back" on the page I was before doing something with one record selected.
I will post later..
Posted Nov 27, 2006 by franck
 

Comment

25 to kashish

hi kashis,

what you are looking for is actually not possible i think. Visualize the situation when you are sorting a column on page 3 after you get the sorted data, which page it should be you think, related to the sorted data???!!?! If it need to be on page 3 what will be page 4 and page 2? anyway on the first place how you will make sure which page it will be. It might be page 3 ...might not be page 3 as sorting ...sorts the entire data , not just that page. and even somehow you sort that part of the data also ..then what will be the previous and next page data?
what i think this is not possible ... but if somebody do it then I will admit that I am wrong ...and yes i will be the first person to grab the logic. :)
Posted Nov 27, 2006 by Suman Paul
 

Comment

26 Please see page 2

Please, please, please see page 2 of this article and/or the google group before asking questions that are either by demonstration, downloadable code, or through someone(me) typing already answered. You may also get a solution faster by asking on the irc channel.

Mario Cesar, see the reply to the comment you have quoted.

Thanks to all who have submitted little patches, I'll add/review these only if there is a need to make changes to the article - as editing it would take it offline for an undetermined duration.
Posted Nov 29, 2006 by Andy Dawson
 

Comment

27 Great

Good article. However, I find it's pity to don't be able to personalize the uris without editing the component.
(In my older pagination system, urls were /module/action/<page>)
Posted Dec 5, 2006 by Damien M.
 

Question

28 Using more than one modelclass

I am new to cake,
I need to implement pagination on a search cuming from 2 models
1) Images
2) Tags

But i am unable to call two models in pagination. Can sumbody help me out..
Posted Dec 7, 2006 by kashish
 

Question

29 Pagination helper sortBy() function

Hi,

I am having a problem with the pagination helper's sortBy method. Suppose I set my own default sortBy field, and then I call the helper's sortBy method on that field to create a table header link. The sortBy method will always return a link w/out any direction information, even if I have just clicked on that header (it should alternate between no direction get parameter (the default) and direction=[opposite of default]). It appears that the getString will not be written properly because of the default values. I was able to change this fault by commenting out these lines (it means get string is sometimes longer than it needs to be, but at least it is correct):

foreach($getParams as $key => $value)
{
if ($pageDetails['paramStyle']=="get")
{
if (isset($pageDetails['Defaults'][$key]))
{
//if (up($pageDetails['Defaults'][$key])<>up($value))
// {
$getString[] = "$key=$value";
// }
}
else
{
$getString[] = "$key=$value";
}
}
Posted Dec 9, 2006 by Michael Patek
 

Question

30 Two pagination elements on the same page.

I have two divs (on the same page) that I would like to use pagination for. Right now if you click the next(20) link you get the next 20 items for both divlist1 and divlist2.

How can I go about setting up pagination to control the two lists independently?
Posted Dec 20, 2006 by Ken
 

Bug

31 Error rendering element

I installed the component and it seems to work fine! In fact I even passed the limit and page to the component and the right data is displaying. Except I get (Error rendering Element: pagination) where the element should be rendered!
Posted Dec 20, 2006 by Tazz
 

Comment

32 Reply

Hi All,

Damien: enabling the urls to be of varying format would add some complexity to the component and helper that I didn't want to introduce. It would also make it easier to cause problems or conflicts (page 1 or item 1?). However, you can pass data to the component in the second parameter (as is done for the named parameter examples http://www.noswad.me.uk/Pagination/Named/index/page:2), instead of letting it use the get data, and modifying the helper to generate links in the format you prefer (and matching the format you expect in the controller) shouldn't be too difficult - but why complicate things.

kashish: you would need to provide a few more details like what sort of associations and what the problem is. Do you mean like this: http://www.noswad.me.uk/Pagination/Normal?sortBy=name&sortByClass=Category

Michael: I can't reproduce that problem, it's probably related to not using the latest code which is here on the bakery, in which case see my reply to Suman Paul above.

Ken: See the source for http://www.noswad.me.uk/Pagination/Ajaxed/Seeingdouble

Tazz: That error isn't specific to pagination, it just means that you called renderElement without an element existing with the name you specified - if you create it (the standard pagination element is one of the links from Settng Up above) that error will go away.

Bake On!
Posted Dec 21, 2006 by Andy Dawson
 

Question

33 Two pagination elements on the same page.

Thx for your previous help.

I also tried to implement Two pagination elements on the same page through ajax, and also tried the solution you gave but that link only contains the demo, from where i can get its usage code?

Posted Dec 27, 2006 by kashish
 

Question

34 I get warnings and notices

Hi, i am not using mod_rewrite, i followed all the instructions you say here, but when i click on the "next" button i get this:

Notice: Undefined index: action in /home/guille/public_html/pig/cake/dispatcher.php on line 144

Notice: Undefined index: controller in /home/guille/public_html/pig/cake/dispatcher.php on line 151

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/guille/public_html/pig/cake/dispatcher.php:144) in /home/guille/public_html/pig/cake/libs/session.php on line 132

Warning: Cannot modify header information - headers already sent by (output started at /home/guille/public_html/pig/cake/dispatcher.php:144) in /home/guille/public_html/pig/cake/libs/session.php on line 133


Can pagination component work without mod_rewrite? what can i do?
Posted Dec 28, 2006 by Guillermo Mansilla
 

Question

35 Two pagination elements on the same page.

Please can you tell me the solution of this ASAP, I need to implement it by tomorrow. I have checked the links you provided but its just the demo page, wat about its usage code.
Posted Jan 1, 2007 by kashish
 

Comment

36 Reply

Happy new year all,

Kashish: see the demos tab.

Guilermo: You may find a few minor problems using the pagination code without mod_rewrite - but not the problem you have mentioned ;). That probably indicates that your install isn't correct. I just double checked by installing version 1.1.12.4205 of cake, not using mod_rewrite, downloading and installing the pagination plugin demonstration code, and did not find any problems. I would advise hopping on the irc channel and asking there.

Bake On!
Posted Jan 3, 2007 by Andy Dawson
 

Bug

37 underline problem with sanitize

I had to change line 461:
$this->paging[$field] = $this->Sanitize->paranoid($_GET[$parameter]);

to:
$this->paging[$field] = $this->Sanitize->paranoid($_GET[$parameter], array('_'));

Because i have a field named *passo_atual* which it's renamed to *passoatual* and occur a SQL error because that field does not exist.
Posted Jan 3, 2007 by Ismael S. Kafeltz
 

Comment

38 Reply (Sanitize)

Please see the comments on the component (http://bakery.cakephp.org/articles/view/67)

Bake On!
Posted Jan 4, 2007 by Andy Dawson
 

Comment

39 Thanks

Thanks a Lot. You are really great.
Happy New Year.. :)
Posted Jan 5, 2007 by kashish
 

Question

40 Same session issue

I wasn't getting this error with the previous version of cake. My cake installation is pretty much vanila, just extract the tar.gz in my www folder.

Previous version: cake_1.1.11.4064.tar.gz
Current Version: cake_1.1.12.4205.tar.gz

The site: with pagination: http://ads.infected-rhythms.com/cake/inbeat/

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /usr/home/ads/www/cake/inbeat/controllers/components/pagination.php:492) in /usr/home/ads/www/cake/cake/libs/session.php on line 146

Warning: Cannot modify header information - headers already sent by (output started at /usr/home/ads/www/cake/inbeat/controllers/components/pagination.php:492) in /usr/home/ads/www/cake/cake/libs/session.php on line 147

Thanks
Posted Jan 8, 2007 by Tazz
 

Comment

41 Session warning

I figured out why we are getting the session warning...

If you cut and paste the component code into your pagination.php file, make sure there is no white space after the ?>

See here why...

http://us3.php.net/manual/en/function.session-start.php
Posted Jan 8, 2007 by Tazz
 

Question

42 Variable missing

Notice: Undefined variable: Posts in C:\wamp\www\cakeblog\app\views\posts\index.thtml on line 12

Warning: Invalid argument supplied for foreach() in C:\wamp\www\cakeblog\app\views\posts\index.thtml on line 12
Posted Jan 17, 2007 by Kenneth Ellis McCall
 

Bug

43 Bug in url generation with array based GET parameters

Hi,

I have added some lines of code in views/helper/pagination.php in order to correct a bug that occured when the plugin had to generate an url with array based GET parameters. Actually this orignal url looks like :
.../controller/action/?data%5BModel%5D%5BField%5D=10023

The links generated by this plugin were for example:
.../controller/action/?data=Array&show=10

It should be:
.../controller/action/?data%5BModel%5D%5BField%5D=10023&show=10

In function _generateUrl, I have changed lines:
>$getString[] = "$key=$value";

By :
> $res = $key;
> while (is_array($value)){
> $keys = array_keys($value);
> $key = $keys[0];
> $res .= "%5B$key%5D";
> $value = $value[$key];
> }// while
> $getString[] = $res."=".$value;

I hope it may help someone...

Regards,

Euphrate
Posted Dec 31, 1969 by euphrate
 

Bug

44 Criteria for pagination not working

Hi,
First of all Andy Thanks a tonne for this great component.I am using using component with great success but i struck some where its not working when i am providing a "group by " condition in criteria field
e.g
$criteria="where name like '%vinod%' group by name"
and then when i use this
$pagination->init($criteria,'modelname',null);
then it displays only 1 result as pagination footer. But main query displays complete data from the table.
I hope you got my point. Any suggestions how we can fix it.


Posted Dec 31, 1969 by vinod
 

Comment

45 minor typing mistake

i forgot to remove "where" in the above query . But problem is still there.
Posted Dec 31, 1969 by vinod
 

Question

46 Amount

How can i change the amount displayed?
Posted Dec 31, 1969 by chris
 

Bug

47 Using Jquery library

Hi Andy,
im using jquery lib for my menu.
if i include the lib before i include the prototype lib, my menu doesnt work anymore.
but if i include the jquery lib after the proto lib, the menu works but the pagination (im using the ajax way) doesnt work anymore.
i guess something in the prototype lib is overriden by the jquery lib and vica versa.
do you maybe have an idea how this problem could be solved ?
or anyone else got an idea ?

regard unk78
Posted Dec 31, 1969 by Felix
 

Bug

48 cant edit

this here is very buggy, i cant edit my post
Posted Dec 31, 1969 by Felix
 

Comment

49 Reply

Ken someone: That isn't a problem or question regarding pagination. Well, to be pedantic there's not even a question :)

Euphrate: Thanks for the contribution. I don't use (and in fact wouldn't advocate) submitting forms by get, but I hope it's useful for others.

vinod: Well for what you have shown, you don't need a group by clause. But the second parameter for init is an array (which you don't need to pass) and that is likely to be the source of a problem.

chris: Page 2 of this article has details of the parameters. Do you mean by default (given it's possible for the user to change the number of results)? If so pass a value for 'show'
in the 3rd (array) parameter.

Felix: "Dunno" I would start here:http://www.google.com/search?q=jquery+and+prototype

Bake On!
Posted Dec 31, 1969 by Andy Dawson
 

Comment

50 Search criteria

Re comments 6 and 23, I have found it easiest to store the search criteria in a session variable.
Example:

---------------------
controller:


class LeadsController extends AppController {

var $name = 'Leads';
var $helpers = array('Html', 'Form','Pagination' );
var $components = array ('Pagination');

function index() {
$this->Lead->recursive = 0;
$criteria=NULL;
$this->set('leads', $this->_paginate_leads($criteria));
}

function search() {
$this->Lead->recursive = 0;
if($this->data['Lead']['search']=='yes') {
$search_term = $this->data['Lead']['company'];
$this->Session->write('search_term', $search_term);
} elseif ($this->Session->read('search_term')) {
$search_term = $this->Session->read('search_term');
} else {
$search_term = '';
$this->Session->write('search_term', $search_term);
}

$criteria =array();
$criteria['Lead']['company'] = "LIKE %{$search_term}%";

$this->set('leads', $this->_paginate_leads($criteria));

$this->render("index");

}

function _paginate_leads ($criteria) {
$options = array(
'resultsPerPage'=>array(50),
'show'=>50
);
list($order,$limit,$page) = $this->Pagination->init($criteria,NULL,$options);
$leads = $this->Lead->findAll($criteria, NULL, $order, $limit, $page);
return $leads;
}

------------------
view for search form:
<form action="<?php echo $html->url('/leads/search'); ?>"
method="post">
<?php echo $html->input('Lead/company'); ?>
<?php echo $html->hidden('Lead/search',array('value'=>'yes')); ?>
<?php echo $html->submit('search');?>
</form>
Posted Mar 15, 2007 by Mike Birch
 

Question

51 Pagination Associations with Primary Model

Possible noob issue for you.

I have a Model that defines a single belongsTo association - this model also has a belongsTo model, and I need sorted pagination on the basis of one of the associated models.

I understand that the pagination helper simply gives me interface control over the findAll() functionality, and i have set the findAll recursivity accordingly, however the $order parameter from pagination to the Controller causes similar errors mentioned above, as the secondary (recursively-determined) Model does not occur in the primary query, only in the subsequent queries by Cake.

Best regards - Leo
Posted Mar 15, 2007 by Leo Brown
 

Comment

52 Pagination Associations with Primary Model

Update - the issue seems to be that the first Model association is actually a $hasMany, which does not alter the primary query; the only association types that I understand to be valid are $hasOne and $belongsTo, however if seems that in this case there is no way of writing the relationship in the form of these:

<pre>
+---------+ +-------------+ +--------+
| Invoice | 1->n | Invoiceitem | 1->1 | Client |
+---------+ +-------------+ +--------+
</pre>

What I'm trying to paginate is Invoice, ordered by Client.Name.

Thanks, LB
Posted Mar 15, 2007 by Leo Brown
 

Bug

53 Adding Ajax

If you want to add Ajax, be sure to call the Ajax helper before the pagination one.
Or at least seems so here!
Posted Mar 19, 2007 by Paolo Gabrielli
 

Question

54 Problem when adding component

When I add 'Pagination' to my components array the following warning appears when logging out (I also use othAuth component for logging and authenticating)

Warning: Cannot modify header information - headers already sent by (output started at C:\Archivos de programa\xampp\htdocs\cake\app\controllers\components\pagination.php:490) in C:\Archivos de programa\xampp\htdocs\cake\cake\libs\controller\controller.php on line 441

Any ideas? Great component, by the way.

Regards.
Posted Mar 22, 2007 by Nicolas
 

Comment

55 why sortByClass wont work

class ConfController extends AppController....


function characteristic() {
$criteria=NULL;
$parameters= array('sortByClass'=>'Characteristic');
list($order,$limit,$page) = $this->Pagination->init($criteria, $parameters );
}

----------------------
FROM `characteristic` AS `Characteristic` WHERE 1 = 1 ORDER BY `Conf`.`id` ASC LIMIT 5

1054: Unknown column 'Conf.id' in 'order clause'
Posted Mar 26, 2007 by Evgenij
 

Question

56 Pagination using custom query

It seems like pagination needs a model class in order for it to work and it executes it's queries (and determins the page, limit, etc) based on that model. I've been trying to get it to work with a custom query (that's used by $this->model->query()) but I can't seem to get it to work. Are there any examples that someone can point me to where the pagination component can work with custom queries?
Posted Mar 28, 2007 by Christoph
 

Comment

57 example

$paginationCount = $this->News->query("SELECT COUNT(*) AS count FROM `news` AS `News` LEFT JOIN `categories` AS `Category` ON `News`.`category_id` = `Category`.`id` WHERE $criteria");

list($order,$limit,$page) = $this->Pagination->init(null,$params,array('total'=>$paginationCount[0][0]['count'],'show'=>$show,'sortBy'=>'date_start','direction'=>'DESC'));
$page = $this->fixPage($show, $page);


/**
* Fix pagination for custom SQL
**/
function fixPage($show, $page)
{
$page--;
$page = $page*$show;

if ($page < 0)
{
$page = 0;
}
return $page;
}
Posted Mar 28, 2007 by Majna
 

Comment

58 sortBySelect

I have implemented this component and helper .can anybody give me a usage code for sortBySelect. I suppose this helps us to have the sorting options in a select box.
Posted Apr 12, 2007 by kashish
 

Question

59 How to give CSS

I am using following code:

$th = Array ('<input type="checkbox" >',
$pagination->sortBy('category_name',"Category Name","Category"),
"Subcategory",
$pagination->sortBy('status',"Status","Category"),
);
echo ($html->tableHeaders($th, Array('class' => "listing_header"), Array('class' => "listing_header")));


My question is:
how can i give my CSS for particular "sort link"?
in above code i gave CSS which applied for <tr> and <th> but i am not able to give CSS for link say "Status". It is taking default CSS given for <a> tag.
Please help.

Early response will be appreciated.

Thanks
Krishan Babbar
Posted Apr 19, 2007 by Krishan Babbar
 

Comment

60 Pagination with multiple table results

hi all,

i'm new to cake, using v1.1.x. i have a search on the main page of my app that searches within 'conditions', 'remedies' & (eventually) 'ratings'. i have models/controllers set up for 'conditions', 'remedies', 'ratings' & 'search'. the 'search' has useTable = False.

the table associations are:
'conditions' hasMany 'remedies'
'remedies' belongsTo 'conditions'
'remedies' hasMany 'ratings'
'ratings' belongsTo 'remedies'

i'm using 'dbsearch' helper to return results for my searches. the problem i'm running into (i think) is that the search result is built after the pagination is initialized. i've tried to find a way to pass the pagination the values after the fact, but it won't let me do it or i can't figure out how to do it. so, it seems to bomb in the code where the pagination looks for 'total' and if 'total' is not set, it's calling findCount for the controller, and it bombs because there is no table associated with that controller. (i'm guessing)

any help would be greatly appreciated...thanks in advance!

here's that code that is failing in my case:
if (isset($this->total))
{
$count = $this->total;
}
else
{
$count = $this->controller->{$this->modelClass}->findCount($criteria,0);
}

here is my search_controller:

<?php
class SearchController extends AppController {
var $name = 'Search';
var $helpers = array('Pagination');
var $components = array ('Pagination');
var $uses = array('Condition');

function index() {
vendor('search'.DS.'DatabaseSearch');
$this->db =& ConnectionManager::getDataSource('default');
$config = $this->db->config;
// settings: host, database, login, password, debug -- if debug is true, it will show the sql query from the search.
/*$this->set('DBSearch', new DatabaseSearch('localhost','oscommerce','root','',false));*/
$this->set('DBSearch', new DatabaseSearch($config['host'],$config['database'],$config['login'],$config['password'],false));
$criteria=NULL;
list($order,$limit,$page) = $this->Pagination->init($criteria, null, array('total'=>'10'));
}

}
?>

and, here is the search index.thtml:

<h1>Search Results</h1>
<?php
$pagination->setPaging($paging); // Initialize the pagination variables

if (isset($_POST["DatabaseSearchNeedle"]))
{
$query = $DBSearch->needle;

echo '<div style="clear: both;"><!-- results --></div>';

//search in table articles, return id, search in listed columns, text and logical operators
$search_result = $DBSearch->DoSearch("conditions","id",array("name","description"),"","");
//search in table articles, return headline, search in listed columns, text and logical operators
$search_result_title = $DBSearch->DoSearch("conditions","name",array("name","description"),"","");

// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("myremedyfind") or die(mysql_error());

echo "<br />";
echo '<p>';

$i = 0;

if ($search_result) {
foreach ($search_result as $result) {

// Retrieve all the data from the "example" table
$nameresult = mysql_query("SELECT * from conditions where id = $result")
or die(mysql_error());

// store the record of the "example" table into $row
$row = mysql_fetch_array( $nameresult );
// Print out the contents of the entry

echo '<a href="'.$html->url('/conditions/view/').$result.'" title="view">';
/*echo $search_result_title[$i]; */
echo $row['name'];
echo '</a><br />';
echo $row['description'];
echo '<br /><br /><br />';
$i++;
}
echo $this->renderElement('pagination'); // Render the pagination element
}
else echo "No results.";

echo '</p>';

} ?>
Posted Apr 30, 2007 by Stacey
 

Bug

61 MSSQL

Pagination doesn't support MSSQL due the lack of the LIMIT function.
Posted May 7, 2007 by leon
 

Comment

62 MSSQL LIMIT equivalent

Pagination doesn't support MSSQL due the lack of the LIMIT function.

Maybe this will help:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=850&lngWId=5
Posted May 8, 2007 by Tim Rand
 

Comment

63 Prettier Navigation Links

I didn't like the navigation links showing up when there was just one page of results, and I didn't like the "previous" arrow showing up on the first page or the "next" arrow showing up on the last page, so I added this function to the pagination helper:

  /**
   * Displays page navigation links
   *
   * @param string $html list of page numbers 
   *       (as generated by PaginationHelper::pageNumbers)
   * @param string $prev text (or html) to put in link to previous page
   * @param string $next text (or html) to put in link to next page
   * @param boolean $escape_text indicates whether we escape html entities of
   *        prev and next.
   * @return string the html for page navigation links.
   **/
  function nav($pages, $prev = null, $next = null, $escape_text = true)
  {
    $nav = '';
    if ($this->_pageDetails['total'] > $this->_pageDetails['show']) {

      $prev = $this->prevPage($prev, $escape_text);
      $next = $this->nextPage($next, $escape_text);

      if ($this->_pageDetails['page'] > 1) {
        $nav .= $prev." ";
      }
      $nav .= $pages;
      $npages = (int)($this->_pageDetails['total'] / $this->_pageDetails['show']);
      $r = $this->_pageDetails['total'] % $this->_pageDetails['show'];
      if ($r) { $npages++; }
      if ($this->_pageDetails['page'] < $npages) {
        $nav .= " ".$next;
      }
    }
    return $nav;
  }



My pagination.thtml element now looks like this:


<div id='pagination'>
<?php
if($pagination->setPaging($paging)):
echo 
$pagination->result()."<br/>";
$leftArrow $html->image("nav/arrowleft.gif", Array('height'=>15));
$rightArrow $html->image("nav/arrowright.gif", Array('height'=>15));
$pages $pagination->pageNumbers(" | ");
$nav $pagination->nav($pages$leftArrow$rightArrowfalse);
if (!empty(
$nav)) { echo $nav."<br/>"; }
endif;
?>
</div>
Posted May 20, 2007 by Michael Patek
 

Comment

64 results

http://www.noswad.me.uk/Pagination/Normal?page=8

Can you please explain how you were able to show the pages on the bottom ?

Page (of 44)«««123456789»»»
Results per page: 2 5 10 20 50

Thanks.
Posted Jun 12, 2007 by Salim
 

Comment

65 reply

http://www.noswad.me.uk/Pagination/Normal?page=8

Can you please explain how you were able to show the pages on the bottom ?

Page (of 44)«««123456789»»»
Results per page: 2 5 10 20 50

Thanks.


Hi Salim, it's the standard pagination element, which is linked to in the section "Setting Up" above. You can get the exact source for that plugin from http://cakeforge.org/projects/noswad . But I don't think it'll contain many surprises ;).
Posted Jun 12, 2007 by Andy Dawson
 

Comment

66 Limit on final page

Hi guys,

I'm using this component for pagination but I've notice something and I don't know if I did something wrong or this is the normal behavior:

Let's say I have as a limit 5 records per page and the query returns 22 records so the view will show me 5 pages, but the last page should return only the 2 records left in order to sum 22 records right? Well, the last page returns me 5 records as well, is this right? How can I change it?

Greetings!
Posted Jul 6, 2007 by Alejandro Lopez Hernandez
 

Question

67 Hooking into ajax onLoading and onComplete

I want to add a activity icon when I click the next and previous buttons. How can I hook into the ajax that is generated so I can add the events?
Posted Jul 26, 2007 by Tazz
 

Comment

68 Pagination problem with Security component and Ajax

Hi!
I had the problem like this:
When I added Security component (var $components = array( "obAuth", "Pagination", "Security");
my links stoped working. I could't change page, number of records and I also could't order results in the table... When I disabled JavaScript in the browser everything went back to normal. Also when I removed "Ajax" from helpers it worked fine. When I was moveing cursor over the links it showed good adresses, but clicking it done nothing - links didn't work.

All I had to do was adding
$settings = array ('ajaxAutoDetect'=> false); 

list($order,$limit,$page) = $this->Pagination->init($criteria, null, $settings );


And once more, GREAT COMPONENT!!!
Posted Aug 25, 2007 by Maciek Grajcarek
 

Comment

69 to Tazz

I want to add a activity icon when I click the next and previous buttons. How can I hook into the ajax that is generated so I can add the events?
Hi,
you can add events in pagination helper. You can add to _generateLink function this:
$options = am($this->ajaxLinkOptions,
array(
"update" => $pageDetails['ajaxDivUpdate'],
"loading" => "preloader.show();",
"complete" => "preloader.hide()"
)
);
Posted Aug 31, 2007 by Zbynek
 

Question

70 HTML validator

This pagination helper getting html validation errors because of "&" in the get string.

I tried it by replacing & by &amp;amp;amp but all in vain and My Ajax based pagination stopped working.

Can You please suggest a method so that my pagination element validates?

Thanks & Regards,
Kashish.
Posted Sep 18, 2007 by kashish
 

Question

71 LIMIT ON FINAL PAGE

Hi guys,

I'm using this component for pagination but I've notice something and I don't know if I did something wrong or this is the normal behavior:

Let's say I have as a limit 5 records per page and the query returns 22 records so the view will show me 5 pages, but the last page should return only the 2 records left in order to sum 22 records right? Well, the last page returns me 5 records as well, is this right? How can I change it?
Can anybody make some help? The same problem like has Alejandro Lopez Hernandez
Greetings!
Posted Oct 1, 2007 by Paulius
 

Question

72 Page header shown several times

Hi,

When I click on any of the links (next page, change sort order, etc), the action takes place correctly. However, inside the div content a whole new page (including the headers in default.thtml and another div content) is rendered. How can avoid this behavior?

Thanks,

Hernan
Posted Oct 4, 2007 by Hernan Grecco
 

Comment

73 To Hernan Grecco

You must frow out $this->layout = "something" from your controller action. Put it as var in controller (var $layout="something") and it should work.
Posted Oct 19, 2007 by Maciek Grajcarek
 

Question

74 Custom query pagination

$paginationCount = $this->News->query("SELECT COUNT(*) AS count FROM `news` AS `News` LEFT JOIN `categories` AS `Category` ON `News`.`category_id` = `Category`.`id` WHERE $criteria");

list($order,$limit,$page) = $this->Pagination->init(null,$params,array('total'=>$paginationCount[0][0]['count'],'show'=>$show,'sortBy'=>'date_start','direction'=>'DESC'));
$page = $this->fixPage($show, $page);


/**
* Fix pagination for custom SQL
**/
function fixPage($show, $page)
{
$page--;
$page = $page*$show;

if ($page < 0)
{
$page = 0;
}
return $page;
}




Hi All,

First of all i pay my thanks to Andy for creating sucha rocking component. I am new to Cake php but implemented this component without any difficulty.

Now i need to implement it using custom query where i got stuck. Can anyone elaborate this example and usage, so that i can implement it using custom query.

Currently i am using this pagination by :
1) Getting products id's from a separate query.
2) Applying pagination from IN() query.
This is making it very heavy as I got more than 50,000 products in my database.

Please help me ASAP(as soon as possible).

Thanks.
Posted Oct 20, 2007 by alisha
 

Question

75 ajax and sortBySelect problem

Hi Andy Dawson,
very cool your pagination - great work!

But i have still problems with sortBySelect function.
I want a select box with the order content and aside a link where i can select the asc/desc order. (all with ajax)

I hope you can help me by this problem - it will be great!

thank u very much.

best regards,
Maidi
Posted Oct 22, 2007 by Maidi
 

Comment

76 ajax and sortBySelect problem solved

ok i solved the problem in an very elegant way.

MfG Maidi
Posted Oct 25, 2007 by Maidi
 

Comment

77 LIMIT ON FINAL PAGE

Hi guys,

I'm using this component for pagination but I've notice something and I don't know if I did something wrong or this is the normal behavior:

Let's say I have as a limit 5 records per page and the query returns 22 records so the view will show me 5 pages, but the last page should return only the 2 records left in order to sum 22 records right? Well, the last page returns me 5 records as well, is this right? How can I change it?
Can anybody make some help? The same problem like has Alejandro Lopez Hernandez
Greetings!


I too am having this same issue
Posted Nov 16, 2007 by ryan faubion
 

Question

78 A big problem

I created my pagination following step by step,but when I click page '2' the url looks like 'www.eg.com/users/listusers?page=2?page-2',click again it looks like 'www.eg.com/users/listusers?page=2?page-2?page=2' click other page number return the same state help me tks a lot!!!
Posted Nov 30, 2007 by tomi
 

Question

79 Strange Issue

We've implemented this and it works great. However, we've also implemented a session based authentication system. The ticket from that session disappears when we hit a page with pagination. Any ideas what might be causeing that or how to remedy it?

This component seems to add a number of sessions. We isolated the app to one user. Before authentication and after authentication we found the sessions table to include one id as expected.

However after navigating to a controller that call the pagination component, the sessions table now has 6 id's for the single user:

23696d97925ef51eeaae95c8b434e57a
6b6ddeddbaa68b041b174efd19324a98
96df778e087bbb73ab17394ec738bdfe
ae081a5307bbe0ba0ca2a366ad3ba070
c6cbaa861045502db60ce3e2c3ff2594
dfa2f8e28b5c645a27be749cb83ab7c9

Why are so many entries required and where do they come from? I don't see anythign that sets then in the code.
Posted Dec 21, 2007 by papajoe
 

Bug

80 Having a very similar strange issue

I have also implemented this paging component into a page after authentication. And it's very strange, sometimes i can browse 4 pages, sometimes just one and then i get logged out ... Seems that there is something destroying oder manipulationg the session, but can't find what ...

Very strange.
Posted Dec 30, 2007 by Andre
 

Question

81 error msg

I am having the following error message:


Warning: Cannot modify header information - headers already sent by (output started at /home/cynziasa/public_html/cynzia/app/controllers/components/pagination.php:491) in /home/cynziasa/public_html/cynzia/cake/libs/session.php on line 147

Fatal error: Call to a member function on a non-object in /home/cynziasa/public_html/cynzia/app/controllers/components/pagination.php on line 212

Any clue what is the problem? I appreciate your kind help!

Thanks!
Posted Jan 16, 2008 by Alberto Bonilla
 

Comment

82 session issue

We've implemented this and it works great. However, we've also implemented a session based authentication system. The ticket from that session disappears when we hit a page with pagination. Any ideas what might be causeing that or how to remedy it?


I was wondering if anyone has managed to solve this issue? I will also be using session authentication and would like to use this component, so it would be good to know how you resolved these issues (if at all?).
Posted Jan 31, 2008 by Rin Tin
 

Comment

83 Pagination destroys the session

I have also implemented this paging component into a page after authentication. And it's very strange, sometimes i can browse 4 pages, sometimes just one and then i get logged out ... Seems that there is something destroying oder manipulationg the session, but can't find what ...

Very strange.


I'm also having the same problem.

I managed to avoid it by setting:
define('CAKE_SECURITY', 'medium');

in core.php.

I belive there is a bug when you use high security, sessions and pagination.
Posted Feb 16, 2008 by Nico
 

Comment

84 Check modelClass if it does not work

I was using pagination in the following situation using the ServiceItem model inside the ServicesController - the pagination worked but all the paging was wrong until I found out I had to set:

$this->Pagination->modelClass = 'ServiceItem';

The component was using the number of records in the Service model rather than the number of results in the ServiceItem model.

So remember to do something like this:



class ServicesController extends AppController {

 var $name = 'Services';
 var $helpers = array('Html', 'Form', 'Jhelper', 'Habtm', 'Pagination' );
 var $uses = array('Service', 'ServiceItem', 'Postcode');
 var $components = array('Map', 'Pagination');

 function admin_index() {
  $this->layout = "admin"; 
  $this->ServiceItem->recursive = 0;

  $criteria=NULL;
  $this->Pagination->resultsPerPage = array(25,50,100);
  $this->Pagination->show = 25;
  $this->Pagination->modelClass = 'ServiceItem';
  
  list($order,$limit,$page) = $this->Pagination->init($criteria); // Added
  
  $data = $this->ServiceItem->findAll($criteria, null, $order, $limit, $page); 

  $this->set('services', $data);
 }
 
}

Posted Feb 29, 2008 by John Elliott
 

Question

85 multiple sortBy

Hi,

I've been using this component for some time now. In my previous projects, field dates use datetime data type such that using a single sort sufficed. Now, however, field dates in my database use date and time separately. I would like to be able to do a sortBy('date') and sortBy('time') at the same time. I've tried sortBy('date, time'), and even modifying the generated link with sortBy=date&sortBy=time and many other solutions, all of which were unsuccessful. The first of the solutions deleted the space and comma (it was made: sortBy('datetime') by Cake), while the second just sorted by, understandably, the last definition of sortBy, which, in this case, is 'time'.

I would like to be able to do a sortBy('date') and sortBy('time') at the same time. In SQL syntax, that would be: ... ORDER BY date, time ...

Is this possible with the current definition?

A favorable help on the matter will be greatly appreciated. Thanks! :)
Posted Apr 1, 2008 by Stephanie
 

Comment

86 using named parameters

Wonderful job, love the smooth ajax functionality. Runs great on my local machine.

The issue I had was when i moved to production, I had to used named parameters, so I get urls like;

http://exampple.com/index.php?/controller/index/show:10/

And I have successfully been able to capture the values for use by the helper to correctly deactivate the corresponding link in the navigation bar. The actual component ignores the parameters, and I can not find where they are set to the get url.


So what I mean is i can generate the right urls(like above), and the page will then italicize the 10 for results, and lets say the 3 for page. The data however remains in a 5 row, page 1 state. Even passing in the whole url manually (no ajax) gets the same results.

I have a method to set them to an array, and could easily merge any existing parameters, but where are they?

Any help would be a great help.

And cheers once again on this great component!
Posted Apr 20, 2008 by Eddie
 

Question

87 Two Pagination element on same page

I have two divs (on the same page)with different id that I would like to use pagination for. Right now if you click the next(5) link you get the next 5 items for both divlist1 and divlist2.

How can I go about setting up pagination to control the two lists independently?
Posted Jun 3, 2008 by Sunil Mahendra