Pagination
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.
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.
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
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 tag
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($criteria, NULL, $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 tag
PHP Snippet:
Download code
<?php
if(isset($javascript)):
echo $javascript->link('prototype.js');
endif;
?>
Comments
Comment
1 GET string creation
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 ("&", $getString);
and it was ok.
regards, danielz
Comment
2 modelClass attribute
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.
Comment
3 modelClass attribute
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'));
Question
4 Unclear error
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 212Comment
5 Reply
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?).
Question
6 Keeping the search criteria from page to page
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 ?
Comment
7 Great Component
Question
8 Sorting by associated attributes
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?
Comment
9 Reply
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
Comment
10 Pagination rocks
Question
11 sortBy not having any effect
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
Question
12 Changing limit
$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?
Comment
13 set resultsPerPage array
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
Comment
14 Reply
[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:
<?phpThe 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.)$settings = array (
'resultsPerPage' => array(100),
'privateParams' = array("show");
);
list($order,$limit,$page) = $this->Pagination->init(NULL,NULL,$settings);
?>
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:
<?phpOr 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.$settings = array (
'show' => 100
);
list($order,$limit,$page) = $this->Pagination->init(NULL,NULL,$settings);
?>
Comment
15 It Works
thank you again very much
Question
16 Pretty URLs
The URLs output properly, but when I click them it doesn't recognise that i have set a pagination variable.
Comment
17 Great Job.
Comment
18 Pretty Params
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.
Question
19 SortBy
As i am new to cakephp , Please can anybody tell me wat shud i do?
Question
20 Getting it to work with Ajax
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:
echo $javascript->link( 'prototype.js' );
echo $javascript->link( 'scriptaculous.js' );
?>
I have the following in my view:
$pagination->setPaging($paging); // Initialize the pagination variables
echo $this->renderElement('pagination'); // Render the pagination element
?>
And this is what the rendered:
Users
List Users
1 |
2Event.observe('link300548541', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=2', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
3Event.observe('link134229918', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=3', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
4Event.observe('link636650378', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=4', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
5Event.observe('link359638782', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=5', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
6Event.observe('link777065471', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=6', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
7Event.observe('link821092498', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=7', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); |
8Event.observe('link1802514728', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=8', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false); | ... |
58Event.observe('link1062195278', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?page=58', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
5
10Event.observe('link2077237105', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=10', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
20Event.observe('link1525874046', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=20', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
50Event.observe('link325316442', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=50', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
100Event.observe('link1796660853', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=100', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
500Event.observe('link1462213788', 'click', function(event){ new Ajax.Updater('users','/narthex/users/index?show=500', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'users']}) }, false);
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
Question
21 Getting it to work with Ajax
>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
>/head<
Comment
22 Reply and Ajax
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,
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).
Question
23 I am having the same Problem
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.
Bug
24 little fix for no mod rewrite
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..
Comment
25 to kashish
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. :)
Comment
26 Please see page 2
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.
Comment
27 Great
(In my older pagination system, urls were /module/action/
Question
28 Using more than one modelclass
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..
Question
29 Pagination helper sortBy() function
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";
}
}
Question
30 Two pagination elements on the same page.
How can I go about setting up pagination to control the two lists independently?
Bug
31 Error rendering element
Comment
32 Reply
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!
Question
33 Two pagination elements on the same page.
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?
Question
34 I get warnings and notices
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?
Question
35 Two pagination elements on the same page.
Comment
36 Reply
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!
Bug
37 underline problem with sanitize
$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.
Comment
38 Reply (Sanitize)
Bake On!
Comment
39 Thanks
Happy New Year.. :)
Question
40 Same session issue
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
Comment
41 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
Question
42 Variable missing
Warning: Invalid argument supplied for foreach() in C:\wamp\www\cakeblog\app\views\posts\index.thtml on line 12
Bug
43 Bug in url generation with array based GET parameters
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
Bug
44 Criteria for pagination not working
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.
Comment
45 minor typing mistake
Question
46 Amount
Bug
47 Using Jquery library
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
Bug
48 cant edit
Comment
49 Reply
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!
Comment
50 Search criteria
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:
method="post"> input('Lead/company'); ?> hidden('Lead/search',array('value'=>'yes')); ?> submit('search');?>
Question
51 Pagination Associations with Primary Model
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
Comment
52 Pagination Associations with Primary Model
What I'm trying to paginate is Invoice, ordered by Client.Name.
Thanks, LB
Bug
53 Adding Ajax
Or at least seems so here!
Question
54 Problem when adding component
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.
Comment
55 why sortByClass wont work
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'
Question
56 Pagination using custom query
Comment
57 example
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;
}
Comment
58 sortBySelect
Question
59 How to give CSS
$th = Array (' if((this.form.elements.type==\'checkbox\')&&(this.form.elements.name.indexOf(\'box_\')==0))
this.form.elements.checked=this.checked;">',
$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
Please help.
Early response will be appreciated.
Thanks
Krishan Babbar Posted Apr 19, 2007 by Krishan Babbar
Comment
60 Pagination with multiple table results
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:
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:
Search Results
$pagination->setPaging($paging); // Initialize the pagination variablesif (isset($_POST["DatabaseSearchNeedle"]))
{
$query = $DBSearch->needle;
echo '';
//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 "
";
echo '
';
';$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 '';
/*echo $search_result_title[$i]; */
echo $row['name'];
echo '';
echo $row['description'];
echo '
';
$i++;
}
echo $this->renderElement('pagination'); // Render the pagination element
}
else echo "No results.";
echo '
} ?>
Bug
61 MSSQL
Comment
62 MSSQL LIMIT equivalent
Maybe this will help:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=850&lngWId=5
Comment
63 Prettier Navigation Links
/**
* 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, $rightArrow, false);
if (!empty($nav)) { echo $nav."<br/>"; }
endif;
?>
</div>
Comment
64 results
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.
Comment
65 reply
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 ;).
Comment
66 Limit on final page
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!
Question
67 Hooking into ajax onLoading and onComplete
Comment
68 Pagination problem with Security component and Ajax
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!!!
Comment
69 to Tazz
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()"
)
);
Question
70 HTML validator
I tried it by replacing & by &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.
Question
71 LIMIT ON FINAL PAGE
Question
72 Page header shown several times
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
Comment
73 To Hernan Grecco
Question
74 Custom query pagination
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.
Question
75 ajax and sortBySelect problem
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
Comment
76 ajax and sortBySelect problem solved
MfG Maidi
Comment
77 LIMIT ON FINAL PAGE
I too am having this same issue
Question
78 A big problem
Question
79 Strange Issue
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.
Bug
80 Having a very similar strange issue
Very strange.
Question
81 error msg
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!
Comment
82 session issue
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?).
Comment
83 Pagination destroys the session
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.
Comment
84 Check modelClass if it does not work
$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);
}
}
Question
85 multiple sortBy
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! :)
Comment
86 using named parameters
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!
Question
87 Two Pagination element on same page
How can I go about setting up pagination to control the two lists independently?
Login To Submit A Comment
Latest Articles
Latest Code
Latest News
Latest Comments