Pagination

by 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:

<?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:


<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:

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


The example presented here is the most simple possible. If you want to see more complex examples of how the code here can be put to use, there is a demo with several permutations here: http://www.noswad.me.uk/Pagination Demos include:
* use on tables with associations
* changing the display text for sort links
* different parameter styles
* including or removing the links to the first and last pages
* how to use with a search form (via ajax)
* using select boxes for parameters instead of links
* preventing access to sort functions
* displaying more than one set of paginated results on the same page (see http://www.noswad.me.uk/Pagination/Ajaxed/SeeingDouble)

Source code is available via the "Download Me" link (for the whole plugin demonstration).

Have Fun!

The parameters Explained

The component and helper have been written as clearly as possible to give users the option to customize it's behaviour. The basic methods are:

Component init

The only method that is necessary to call, it has 3 parameters.

The Constraint

This is the sql that will be the "where" clause in the find count statement*

Web Parameters (Optional)

These are the publicly accessible parameters that came from the web, it isn't necessary to pass them if you are using GET style parameters.

If you choose not to use GET parameters, it's necessary to provide the parameters to the component as it isn't possible to automatically determine them. All of the parameters are optional and are of the form:

PHP Snippet:

<?php 
array (
"page"=>$pageNumber// Integer
"sortBy"=>$fieldName// string the name of a field
"sortByClass"=>$modelName// string the name of the model
"direction"=>$direction// ASC or DESC - sort direction
"show"=>$show // Integer Number of results to display per page
)
?>

Initialization Parameters

These are the private parameters that should never be accessible from the web. These parameters can be used to set the default values if different from those in the component itself or to apply restrictions or different behaviour.
All of the parameters are optional and are of the form:

PHP Snippet:

<?php 
array (
"page"=>$pageNumber// Modify Default
"sortBy"=>$fieldName// Modify Default
"sortByClass"=>$modelName// Modify Default
"direction"=>$direction// Modify Default
"show"=>$show // Modify Default

"privateParams" $privateParams// Array of parameter names which cannot be passed via the url
"total"=>$total // Integer Overriding the number of results, bypasses the sql count statement
"maxPages"=>$max // Integer The maximum number of pages to be included in the list of pages
"showLimits"=>$limits // Boolean Whether to display links to the first and last pages when they are not in the current page range.
"resultsPerPage"=>$resutsPerPage// Array of the possible number of results to be displayed per page.
"paramStyle"=>$Style // String Determins how links are generated - get or pretty. Pretty means urls of the form /action/param{seperator}value
"paramSeperator"=>$Seperator// String The seperator used for pretty url links - defaults to ":"
"url"=>$url // The base url used for links. If undefined it is derived from the current action, and controller name, taking care of admin and plugin parameters

"ajaxAutoDetect"=>$Detect// Boolean Use AJAX links if available defaults to true
"ajaxDivUpdate"=>$DivId// String The id of the div to update for AJAX updates. Defaults to content.
"ajaxFormId"=>$FormId // String The id of a form which will be serialized and passed with all pagination links, if AJAX is enabled.
)
?>

Helper sortBy

This method generates a link that will modify the sort order and reset the results to page 1. It has 3 parameters

The Field to sort by

The display text for the link (defaults to the Field name)

The model for the sort (defaults to the controller default model)

1 | 2

Report

More on Tutorials

Tags

Advertising

Comments

  • salentinux posted on 05/15/10 10:57:00 AM
    In the links generated by the helper, the & character is replaced by &amp; entity and therefore the links don't work either with ajax or static html link. How can I force the & char to remain unchanged?
    Thanks to all.
  • jhonlincon82 posted on 03/18/10 02:28:58 AM
    Pagination is the system by which the information on a newspaper, bookpage, manuscript, or otherwise handwritten, printed or displayed document is laid out.

    In a strict sense of the word, it can mean the consecutive numbering to indicate the proper order of the pages, which was rarely found in documents pre-dating 1500, and only became common practice circa 1550, when it replaced foliation, which numbered only the front sides of folios.

    microsoft certification
  • abcoder posted on 01/25/10 03:44:24 AM
    I've done it in a different way using the core pagination method of cake. Please have a look at http://abcoder.com/php/cakephp/cakephp-advanced-pagination-sort-by-derived-field/ for details...

    Thanks
    Adnan
  • azlanms posted on 05/17/09 09:09:03 PM
    Hi,

    Firstly, thank you for providing this article and code. It's helped me a lot.

    Secondly, I'm wondering why do I get SQL error during initializing. The specific error given during DEBUG mode 2 is:

    1064: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '[count] FROM `engr_projects` AS `EngrProject` LEFT JOIN `manuf

    The corresponding SQL statement is:

    SELECT COUNT(*) AS [count] FROM `engr_projects` AS `EngrProject` LEFT JOIN `manufacturers` AS `Manufacturer` ON `EngrProject`.`region_id` = `Manufacturer`.`id` WHERE 1 = 1

    When tested on another platform, no error was given but the corresponding SQL statement become:

    SELECT COUNT(*) AS `count` FROM `engr_projects` AS `EngrProject` LEFT JOIN `manufacturers` AS `Manufacturer` ON `EngrProject`.`region_id` = `Manufacturer`.`id` WHERE 1 = 1

    Note the 'count' without square braces. The server that was not working is running CakePHP 1.1.13.4450 with MySQL 4.0.16. I don't intend to migrate to newer CakePHP version since a lot of development has been done.

    Is there any incompatibility with the version or bug in the code?

    Thanks for your help.
    • azlanms posted on 05/20/09 08:18:44 PM
      Hi,

      Firstly, thank you for providing this article and code. It's helped me a lot.

      Secondly, I'm wondering why do I get SQL error during initializing. The specific error given during DEBUG mode 2 is:

      1064: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '[count] FROM `engr_projects` AS `EngrProject` LEFT JOIN `manuf

      The corresponding SQL statement is:

      SELECT COUNT(*) AS [count] FROM `engr_projects` AS `EngrProject` LEFT JOIN `manufacturers` AS `Manufacturer` ON `EngrProject`.`region_id` = `Manufacturer`.`id` WHERE 1 = 1

      When tested on another platform, no error was given but the corresponding SQL statement become:

      SELECT COUNT(*) AS `count` FROM `engr_projects` AS `EngrProject` LEFT JOIN `manufacturers` AS `Manufacturer` ON `EngrProject`.`region_id` = `Manufacturer`.`id` WHERE 1 = 1

      Note the 'count' without square braces. The server that was not working is running CakePHP 1.1.13.4450 with MySQL 4.0.16. I don't intend to migrate to newer CakePHP version since a lot of development has been done.

      Is there any incompatibility with the version or bug in the code?

      Thanks for your help.
      Sorry guys, it's my fault. I've made some changes in CakePHP database interface file. I've restored it and the error has gone.
  • sagar_spc89 posted on 05/12/09 02:47:55 AM
    First of all thanks for the best script provided by you.

    I m new to cake and i was trying to implement css for the script provided by you.But i cant understand how to apply css for th page number which is selected.Plz help ASAP
  • nayhtet posted on 02/23/09 09:53:41 PM
    Hi,

    i would like to show like this: < Previous | Next > instead of showing page numbers.
    How can i do that?
    Thanks.

    ###
    dunno whether it is true or not.
    i used prevPage() and nextPage()
  • sm.mahendra posted on 06/03/08 11:50:48 PM
    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?
  • masterkeedu posted on 04/20/08 03:52:39 PM
    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!
  • steph6u posted on 04/01/08 06:04:10 AM
    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! :)
  • flipflops posted on 02/29/08 05:22:44 AM
    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);
     }
     
    }

  • dsinning posted on 01/16/08 11:58:25 AM
    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!
  • Andrew2day posted on 12/30/07 02:54:13 PM
    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.
    • Nicodemuz posted on 02/16/08 12:25:53 PM
      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.
  • papajoe posted on 12/21/07 11:15:13 PM
    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.
    • rintin posted on 01/31/08 04:45:54 AM
      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?).
  • tomisong posted on 11/30/07 12:03:56 PM
    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!!!
  • Maidi posted on 10/25/07 03:19:40 AM
    ok i solved the problem in an very elegant way.

    MfG Maidi
  • Maidi posted on 10/22/07 01:38:23 AM
    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
  • mgrajcarek posted on 10/19/07 11:57:21 AM
    You must frow out $this->layout = "something" from your controller action. Put it as var in controller (var $layout="something") and it should work.
  • hgrecco posted on 10/04/07 03:35:33 PM
    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
  • kashish posted on 09/18/07 08:30:55 AM
    This pagination helper getting html validation errors because of "&" in the get string.

    I tried it by replacing & by &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.
  • mgrajcarek posted on 08/25/07 08:11:12 AM
    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!!!
  • infectedrhythms posted on 07/26/07 12:14:04 AM
    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?
    • zbystr posted on 08/31/07 12:52:00 PM
      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()"
      )
      );
  • ulfo posted on 07/06/07 01:17:59 PM
    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!
    • Apulis posted on 10/01/07 12:43:07 AM
      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!
      • actuel posted on 11/16/07 12:09:30 PM
        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
        • icc97 posted on 12/03/09 01:06:57 PM
          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

          Yep, me too - did anyone find a solution?? I'm using SQL Server I don't knon if that would cause any issues.
          • icc97 posted on 05/17/10 09:00:13 AM
            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

            Yep, me too - did anyone find a solution?? I'm using SQL Server I don't knon if that would cause any issues.

            It looks like it is purely an issue with SQL-Server having TOP and MySQL having LIMIT. CakePHP doesn't implement the last page correctly using SQL-Server SQL. The only fix I found was to put code into the View that restricts the list to just those that should appear on the last page using the various pagination variables
  • salimk786 posted on 06/12/07 03:08:41 PM
    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.
  • mpatek posted on 05/20/07 11:49:28 AM
    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>
  • spinnetje posted on 05/07/07 03:14:40 AM
    Pagination doesn't support MSSQL due the lack of the LIMIT function.
  • monkeymynd posted on 04/30/07 04:31:58 PM
    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:

    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 variables

    if (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 '

    ';

    } ?>
  • krishan_babbar posted on 04/19/07 12:53:08 AM
    I am using following code:

    $th = Array (' if((this.form.elements[i].type==\'checkbox\')&&(this.form.elements[i].name.indexOf(\'box_\')==0))
    this.form.elements[i].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 and but i am not able to give CSS for link say "Status". It is taking default CSS given for tag.
    Please help.

    Early response will be appreciated.

    Thanks
    Krishan Babbar
  • anjali posted on 04/12/07 06:55:56 AM
    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.
  • Christoph posted on 03/28/07 01:53:58 PM
    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?
    • majna posted on 03/28/07 03:15:53 PM
      $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;
      }
      • alisha posted on 10/20/07 12:21:22 AM
        $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.
  • Genius_kld posted on 03/26/07 07:22:24 PM
    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'
  • nico.ej posted on 03/22/07 03:37:51 PM
    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.
  • paolo posted on 03/19/07 12:53:55 PM
    If you want to add Ajax, be sure to call the Ajax helper before the pagination one.
    Or at least seems so here!
  • leo.brown posted on 03/15/07 12:09:41 PM
    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
    • leo.brown posted on 03/15/07 12:32:45 PM
      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:

       +---------+      +-------------+      +--------+
      | Invoice | 1->n | Invoiceitem | 1->1 | Client |
      +---------+ +-------------+ +--------+

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

      Thanks, LB
  • mike_birch posted on 03/15/07 04:12:07 AM
    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:
    method="post"> input('Lead/company'); ?> hidden('Lead/search',array('value'=>'yes')); ?> submit('search');?>
  • ellisgl posted on 01/17/07 03:45:18 PM
    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
  • infectedrhythms posted on 01/08/07 02:42:26 AM
    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
  • infectedrhythms posted on 01/08/07 02:25:52 AM
    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
  • kashish posted on 01/05/07 01:33:38 AM
    Thanks a Lot. You are really great.
    Happy New Year.. :)
  • AD7six posted on 01/04/07 01:53:21 AM
    Please see the comments on the component (http://bakery.cakephp.org/articles/view/67)

    Bake On!
  • shalanga posted on 01/03/07 06:14:18 PM
    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.
  • AD7six posted on 01/03/07 03:33:37 AM
    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!
  • kashish posted on 01/01/07 11:13:16 PM
    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.
  • gmansilla posted on 12/28/06 11:28:31 AM
    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?
  • kashish posted on 12/27/06 06:34:46 AM
    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?

  • sankaman2k posted on 12/20/06 05:14:59 PM
    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?
    • infectedrhythms posted on 12/20/06 08:58:51 PM
      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!
  • mpatek posted on 12/09/06 10:14:00 AM
    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";
    }
    }
  • kashish posted on 12/07/06 06:26:31 AM
    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..
  • kazhar posted on 12/05/06 08:27:18 AM
    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/)
  • xentek posted on 11/29/06 01:29:13 PM
    I don't see any examples, just an intro paragraph when I visit the demo link. When I click demos in your navigation, i get a list of all the demos, when i click the download link, i get a download that finishes quickly but can't be unzipped because of (Error 1 - Operation not Permitted).

    Using Firefox 2.0 on Mac OS X (PPC) 10.4.8
    • AD7six posted on 12/21/06 04:46:51 AM
      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!
    • AD7six posted on 12/21/06 04:27:11 AM
      I don't see any examples, just an intro paragraph when I visit the demo link. When I click demos in your navigation, i get a list of all the demos, when i click the download link, i get a download that finishes quickly but can't be unzipped because of (Error 1 - Operation not Permitted).

      Using Firefox 2.0 on Mac OS X (PPC) 10.4.8

      Hi Eric,

      I didn't see this comment until right now.

      The intro page contains a sub menu (On the right) of the various permutations.

      The download finishes quickly because it's not very big (about 50K).

      There was a problem extracting the zips directly on a mac, possibly related to invalid dates in the zip file - There's a note on the download page regarding this. I updated the zip generating code recently, but you should be able to extract from the command line if the problem still persists. I don't remember if I added the note and changed the code before or after your comment - please let me know if you have problems or not.
  • AD7six posted on 11/29/06 02:22:11 AM
    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.
  • sumanpaul posted on 11/27/06 03:57:19 AM
    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. :)
  • francky06l posted on 11/27/06 03:13:38 AM
    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..
  • Christoph posted on 11/25/06 06:15:48 AM
    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/title<
    >/head<
    • AD7six posted on 11/26/06 05:05:11 AM
      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).
  • Christoph posted on 11/25/06 06:11:58 AM
    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:

    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





    Id Last Login Name Email City State Country Comments Theme Onsite Trades Hide Inventory Created Modified
    blah blah blah blah blah blah blah blah blah blah blah blah blah




    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
  • kashish posted on 11/24/06 04:40:22 AM
    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?
  • AD7six posted on 11/22/06 11:58:55 AM
    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.
  • dapatrick posted on 11/22/06 09:06:32 AM
    Great job on this tutorial, and its accompanying code.
  • cornernote posted on 11/21/06 07:39:59 AM
    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.
  • sumanpaul posted on 11/04/06 11:15:55 PM
    Thanks Andy ...it is working perfectly after the update :)

    thank you again very much
  • sumanpaul posted on 11/03/06 10:28:41 PM
    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
    • AD7six posted on 11/04/06 05:51:02 AM
      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.
  • Romen posted on 11/03/06 02:55:20 PM
    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?
  • sumanpaul posted on 10/31/06 02:55:49 PM
    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
  • the_undefined posted on 10/27/06 06:20:26 AM
    Thanks Andy for devoting your time to this, pagination is awesome ; ).
  • AD7six posted on 10/26/06 09:46:58 AM
    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
  • ajessup posted on 10/26/06 02:12:38 AM
    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?

  • msamour posted on 10/23/06 06:24:11 PM
    Thanks man I really like the way this component works. Simple and easy.
  • ihari posted on 10/23/06 04:49:02 AM
    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 ?

    • mariocesar posted on 11/27/06 12:43:02 AM
      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.
  • wenzel posted on 10/19/06 03:06:15 PM
    Hey there,

    good work! Short note: it's "relevant", not "relavent".

    Fred
  • Vortex posted on 10/16/06 08:52:20 AM
    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.

    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
  • lorenzo posted on 10/12/06 09:53:07 PM
    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.
    • AD7six posted on 10/16/06 02:11:41 PM
      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?).
    • jcsiegrist posted on 10/13/06 04:08:04 AM
      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'));

  • danielz posted on 10/11/06 08:10:18 PM
    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;", $getString);

    and it was ok.

    regards, danielz
  • gwoo posted on 09/27/06 11:36:37 AM
    I think we need to do some simplicfication to this tutorial or create another simpler approach. 5 pages for pagination seems a bit of overkill. It does handle a lot of functionality, but ideally a two pager would be all thats needed.

    What do you think?
  • euphrate_ylb posted on 11/30/99 12:00:00 AM
    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
  • vinod posted on 11/30/99 12:00:00 AM
    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.


    • vinod posted on 11/30/99 12:00:00 AM
      i forgot to remove "where" in the above query . But problem is still there.
  • pixol posted on 11/30/99 12:00:00 AM
    How can i change the amount displayed?
  • unk78 posted on 11/30/99 12:00:00 AM
    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
  • AD7six posted on 11/30/99 12:00:00 AM
    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!
login to post a comment.