Wednesday, July 1, 2009

Zend Pagination example

Paginator component is available with Zend Framework v1.6. This component wasn’t available in v1.5. I appreciate Zend for provide such a nice component for pagination. This component, like other component, is so loosely coupled that you can use it wherever you want without worrying about any other component at all.
If you have already created pages and you want to apply pagination to them, it would not be a big deal.
Pagination is three step process.

1. you will need to create template file. In template file you can specify layout of your pagination. i.e. how your first, previous, next and last etc will be displayed.

2. instantiate your pagination class in the controller and pass data source- data source can be an array, values fetched form the database etc.

3. make some change in your template file, where you are showing your records.
Lets have a simple example.
First create a template file pagination.phtml in your “/application/view/script/” folder and place the following code
<div class="pagination" style="width:100%">
<div style="float:left;width:28%">
</div>
<div style="float:right;width:70%;">
<!-- First page link -->
<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->first)); ?>">Start</a> |
<?php else: ?>
<span class="disabled">Start</span> |
<?php endif; ?>

<!-- Previous page link -->

<?php if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->previous)); ?>">&lt; Previous</a> |
<?php else: ?>
<span class="disabled">&lt; Previous</span> |
<?php endif; ?>
<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?= $this->url(array('page' => $page)); ?>"><?= $page; ?></a>
<?php else: ?>
<?= $page; ?>
<?php endif; ?>
<?php endforeach; ?>
<!-- Next page link -->
<?php if (isset($this->next)): ?>
| <a href="<?= $this->url(array('page' => $this->next)); ?>">Next &gt;</a> |
<?php else: ?>
| <span class="disabled">Next &gt;</span> |
<?php endif; ?>
<!-- Last page link -->
<?php if (isset($this->next)): ?>
<a href="<?= $this->url(array('page' => $this->last)); ?>">End</a>
<?php else: ?>
<span class="disabled">End</span>
<?php endif; ?>
&nbsp; Page <?= $this->current; ?> of <?= $this->last; ?>
</div>
</div>

The code above is self explanatory. We are creating links for the pagination.

Next add the following code in your controller.
$sql = 'SELECT * FROM table_name ';
$result = $db->fetchAll($sql);
$page=$this->_getParam('page',1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(10));
$paginator->setCurrentPageNumber($page);

$this->view->paginator=$paginator;

In the code above we first fetch records from our database. Then instantiate our paginator by writing
$paginator = Zend_Paginator::factory($result);

And pass it results we have fatched.
We then set number of items per page and current page. On our first visit $page will have value 1.
At the end we assign this paginator to our view template.
And now in view template add the following code
foreach($this->paginator as $record)
{
echo $record['firstname'].'\n';
echo $record['lastname']. '\n'
...
...
}

<?= $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?

We are applying foreach loop to our paginator and echo our records. I assume that you have fistname, lastname columns in your table where you are fetching records form.Last line is compulsory. you need to call the paginator contorller and give it the $paginator, style of the pagination and the file name of the pagination template.

89 comments:

  1. hi,
    thanks, for this tutorial. While reading I implemented zend_paginator.

    I notice its add extra - /action/page/pageno to the url.
    Which makes my images and css to not properly.
    What would be cause. does its url() function used in pagination.phtml file.

    How to get loaded my images and css?

    currently it load url as localhost/app/public/index/index/page/2 etc..
    if i modified my url ... /index?page=2 - i can see my images and css. Why it is like ?

    thanks
    rakesh

    ReplyDelete
  2. script pagination.phtml not found in path (c:\xampp\htdocs\haney\testing1\application\views\scripts\;.\views\scripts\)


    what happend ? i dont know

    could u plz tell me whats wrong ?

    ReplyDelete
    Replies
    1. i have the same problem, could anybody reply?

      Delete
    2. Specify the relative path of pagination.phtml like

      paginationControl($this->paginator, 'Sliding', '/index/pagination.phtml'); ?>

      Delete
  3. All correct but there's:

    $paginator->setItemCountPerPage(10));

    should be

    $paginator->setItemCountPerPage(10);

    Regards,
    Jacob

    ReplyDelete
  4. Thanks, this is just what I needed, a tutorial for someone who never used this feature before. Official Zend tutorial sure didn't help me but this one did...

    ReplyDelete
  5. Thanks a lot..simple and easy to understand yet very powerful

    ReplyDelete
  6. The Tutotial seems all nice and simple, and ZF team as kept the tool that way.

    My only concern is when, i need to see 10 rows, it should fetch 10 rows from the database, it shoulnt be like we are fetching then entire result set of 100 rows, to display only 10 rows and again fetch a 100 rows to display next set of 10 rows.

    its there a alternative to fetching all rows and passing it to the paginator?

    ReplyDelete
  7. But how can make this pagination with another parameter

    ReplyDelete
  8. We are applying foreach loop to our paginator and echo our records. I assume that you have fistname, lastname columns in your table where you are fetching records form.Last line is compulsory. you need to call the paginator contorller and give it the $paginator, style of the pagination and the file name of the pagination template.

    ReplyDelete
  9. Maybe this code works, but who fetches all database results to build a pager and show only a smaller set of them?? It doesn't make any sense...

    ReplyDelete
  10. Refer to the Manual, there is an Zend_Paginator_Adapter_DbSelect wich accepts an select stmt and is only fetching the nesecary rows from database.

    ReplyDelete
  11. Thanks Brother, I was able to do it 2 min, Its really nice

    ReplyDelete
  12. Thanks man. Like Iyngaran Iyathurai said before me, I was able to implement this in 2 min. Good stuff!

    ReplyDelete
  13. It works, save me alot! Thanks man!

    ReplyDelete
  14. Really Thanks Dear, It works Greatly.....
    U make my Day ...
    Thanks Again...

    ReplyDelete
  15. Nice tutorial, but it would be great if you also explained how to use Zend_Paginator_Adapter_DbSelect! ;)

    ReplyDelete
  16. Excellent Tutorial... thanks for posting...

    ReplyDelete
  17. useful tutorial to use paging in zend framework.. thanks mate

    ReplyDelete
  18. great tutorial ! Of course - on official plugin wikipage I'm not find good anserws ( for me ;) ).
    Thanks for tutorial !

    ReplyDelete
  19. Thanks a lot! It works fine and helped me a lot!
    I hope you can explain how works Zend_Paginator_Adapter_DbSelect, one of these days in another clear tutorial like this one!

    ReplyDelete
  20. don't pull the whole table in.

    make a Zend_Db_Select instance and supply that to

    Zend_Paginator_Adapter_DbSelect

    without running the query - doing it this way will be higher performance.

    ReplyDelete
  21. Works like a charm!

    Thanks for sharing such a simple pagination tutorial.

    Shouvik

    ReplyDelete
  22. Faheem,

    thank you for this simple tutorial. It worked without problems. Thank you, especially because Zend Framework is sometimes so bulky.

    Thanks,
    gaga

    ReplyDelete
  23. I have done function in the controller like this,

    public function paginationControl(){
    $db = Zend_Db_Table_Abstract::getDefaultAdapter();
    $select = new Zend_Db_Select($db);
    $statement = $select->from('pharmacy');
    $statement = $statement . "order by id desc";
    $results = $db->query($statement);
    $rows = $results->fetchAll();

    $page=$this->_getParam('page',1);
    $paginator = Zend_Paginator::factory($rows);
    $paginator->setItemCountPerPage(10);
    $paginator->setCurrentPageNumber($page);

    $this->view->paginator=$paginator;
    }

    I have given pagination control in the view script as below,

    $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml');

    but its not displaying the pagination.. what is the problem in it?????

    ReplyDelete
  24. nice one @trytry.

    @Anonymous -
    I think what he is trying to say is echo the pagination control:

    echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml');

    ReplyDelete
  25. good stuff, thanks for this, admittedly i struggled for a half hour until i realised i overlooked placing that pagination.phtml in the views/scripts folder not (in my case) views/scripts/news...

    For some reason its not counting the pages for me but other then that its a treat!

    Cheers chief!

    ReplyDelete
    Replies
    1. can you tell me where exactly to put that page?

      Delete
  26. Hey just incase anyone else had the same problem with the pagination working in one direction i found this useful, i think it might be something to do with the for loop on the view page and also the code on the pagination view/layout/helper file...

    http://www.zfforums.com/zend-framework-components-13/core-infrastructure-19/zend-pagination-1875.html

    i ended up with something like this..

    ************ On the pagination file (that sits in the views fold **************
    **** I think it was to do with not having the count around the loop ********
    pageCount): ?>


    previous)): ?>
    < Previous |

    < Previous |



    pagesInRange as $page): ?>
    current): ?>
    |

    |




    next)): ?>
    Next >

    Next >




    ************ On my index.phtml page in the views/news folder **************

    paginator)):
    foreach($this->paginator as $record) {
    echo '' . '' . $record->title . '' . '';

    echo '<-p>' . $record->content . '';
    echo 'Read more';
    echo "\n";
    } endif;
    ?>

    paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?>

    ********** And finally my contoller ***********

    $model = new Default_Model_News;
    $newsitems = $model->fetchAll();
    $page = $this->_getParam('page',1);
    $paginator = Zend_Paginator::factory($newsitems);
    $paginator->setItemCountPerPage(10);
    $paginator->setCurrentPageNumber($page);

    $this->view->paginator=$paginator;

    Hope this help yall!

    Ps i had to mess my html tags up in order to post, so things like and <-p> and whatnot are just to get past the posting rules

    ReplyDelete
  27. That's a good article. If someone has any problem with the Pagination Control (paginationControl...)
    Remember create an instance of Zend_View_Helper_PaginationControl() in the controller and pass it to the view. For example:

    $paginationControl = Zend_View_Helper_PaginationControl();

    $this->view->paginationControl = $paginationControl;

    www.javierbracero.blogspot.com

    ReplyDelete
  28. Thanks for the tutorial, it was really useful!

    ReplyDelete
  29. I don't know whay...i can't
    echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml');

    is their some could help me?

    ReplyDelete
  30. Hi Nice tutorial
    I am using pagination with zend tabContainer here pagination not working. need help

    ReplyDelete
  31. Thanks for the tutorial. It is a good starting point.

    For those who want to efficiently fetch the data from the DB, provide the zend_db_Select object as a parameter to the profiler factory. this link explains it

    http://framework.zend.com/manual/en/learning.paginator.simple.html

    ReplyDelete
  32. Thanks. Very helpfull.... :)

    ReplyDelete
  33. Great tutorial thanks for sharing it with us .....

    ReplyDelete
  34. I have a problem that where to write this code

    foreach($this->paginator as $record)
    {
    echo $record['firstname'].'\n';
    echo $record['lastname']. '\n'
    ...
    ...
    }

    paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?

    ReplyDelete
  35. Very nice example,

    Thanks

    Hasan Akmaz

    ReplyDelete
  36. Displaying the pagination links how you have done breaks my application.

    ReplyDelete
  37. foreach($this->paginator as $record)
    {
    echo $record['firstname'].'\n';
    echo $record['lastname']. '\n';
    }
    by doing so this is generating Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\zend_login\application\views\scripts\task\list.phtml on line 47
    line 47 is $record['firstname']
    its object and we are accesing it as assoc array.i also convert it to array but than this line giving me error
    paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?>

    ReplyDelete
  38. This comment has been removed by the author.

    ReplyDelete
  39. the above code work good but the URL look wrong as rakesh mishra on first comment said so please if any one know hepl us

    its show as ->localhost/zfoperation/public/index/index/page/2

    but it should be as -> its show as ->localhost/zfoperation/public/index/page/2

    From->J3

    ReplyDelete
  40. These examples really helped a lot ..... Thanks Faheem :)

    ReplyDelete
  41. Thank you so much Faheem ..... these examples r really simple & helped a lot to me for finishing the assigned task ... Regards :)

    ReplyDelete
  42. thanks for this simple tutorial... It's work without any error... :-)

    ReplyDelete
  43. Hi,

    I need Pagination for Zend Framework 2.0

    Anyone can tell how to do ?

    ReplyDelete
  44. nice post...thanks.

    ReplyDelete
  45. good tutorial..!!! but my links are not working(next,1,2,...,End) can anyone help me..??

    ReplyDelete
  46. Dear All,
    In my page i got the pagination view..It display first page perfectly..! but when i click other links(2 3 4 5 6 |Next>| End) i got an Application Error. i can't understand what happening. Someone can help me Plzz

    ReplyDelete
  47. Thank you very much. really helpfull :)

    ReplyDelete
  48. Really good example ...
    thanx....

    ReplyDelete
  49. Hello friend,
    i want to one another help ...
    for data soring with pagination in zendframework ...
    i fetch my data from database table and i want to data sorting code by click on field name asc/desc order..
    Please help....
    thanks ...

    ReplyDelete
  50. Thanks you very much, its really awesome and work great. :)

    ReplyDelete
  51. Thank you.it is simple and easy to learn

    ReplyDelete
  52. thanks lot. easy way, good explanation

    ReplyDelete
  53. This comment has been removed by the author.

    ReplyDelete
  54. Warning: Invalid argument supplied for foreach() in C:\wamp\www\appsZend\application\modules\almox\views\scripts\paginator.phtml on line 20

    ReplyDelete
  55. thanks a lot this tutorial help me a lot in implementing pagination in Zend framework.

    ReplyDelete
  56. Hi Friends. Thanks for this tutorial. I am stuck in some issue please help me... :(
    Thanks in advance

    I am using below given code:

    $db = Zend_Registry::get('db');
    $expression = new Zend_Db_Expr('COUNT(*) AS ' . $db->quoteIdentifier(Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN));
    $rowCount = $db->select()->from('user', $expression);
    $adapter->setRowCount($rowCount);
    $paginator = new Zend_Paginator($adapter);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));
    $paginator->setItemCountPerPage(10);
    $paginator->setPageRange(3);
    $this->view->paginator = $paginator;

    When i write below given line in view I get the Fatal error:

    echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml');


    Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (error)' in F:\xampp\php\PEAR\Zend\Controller\Dispatcher\Standard.php:248 Stack trace: #0 F:\xampp\php\PEAR\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #1 F:\xampp\php\PEAR\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch() #2 F:\xampp\php\PEAR\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run() #3 F:\xampp\htdocs\ZendEg\public\index.php(26): Zend_Application->run() #4 {main} Next exception 'Zend_Controller_Exception' with message 'Invalid controller specified (error)#0 F:\xampp\php\PEAR\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #1 F:\xampp\php\PEAR\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch() #2 F:\xampp\ph in F:\xampp\php\PEAR\Zend\Controller\Plugin\Broker.php on line 336

    ReplyDelete
    Replies
    1. Hi, i am also getting this error. How did you solve it ??

      Delete
  57. Hi All,
    It's a cool tutorial. As I am very new to zend framework I found it very easy and useful. But It refreshes the whole page every time I want to go to new page. Is there any way to do this without page refresh like ajax. Another thing is that If I have 100 pages then it will show 100pages like 1,2,3,4,5,...,100. It's not looks good.
    It will better if when the user is at say page 1 it will only show 2,3,4 and when the user is at page 2 it will show 3,4,5 like that.

    Can anybody fix this issues. I will be very helpful for the newbies like me.

    Thanks for this nice tutorial

    ReplyDelete
  58. i have thos control functin
    public function listAction()
    {

    $params = array('host' =>'localhost',
    'username' =>'root',
    'password' =>'',
    'dbname' =>'faizan'
    );
    $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
    $sql = 'SELECT * FROM user';
    $result = $DB->fetchAll($sql);
    $page=$this->_getParam('page',1);
    $paginator = Zend_Paginator::factory($result);
    $paginator->setItemCountPerPage(4));
    $paginator->setCurrentPageNumber($page);

    $this->view->paginator=$paginator;
    }

    and this view code
    paginator;

    foreach($datas as $dtas){ ?>

    <? }
    But It doesnt work can any one help...

    ReplyDelete
  59. am getting this warning.
    Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\justbuyentry\application\modules\admin\views\scripts\exhibition\exhibitions.phtml on line 51
    i.e pagesInRange

    ReplyDelete
  60. superb Tutorial..Its working Perfectly...Thanks

    ReplyDelete
  61. i'm also getting the warning :
    Invalid argument supplied for foreach() in C:\wamp\www\Vote\application\views\scripts\resto\index.phtml on line 36
    and to me it is about the pagesInRange value.
    I'm new in zf could you please help ?
    thanks

    ReplyDelete
  62. hi I finally found the issue.
    thanks for this all !

    ReplyDelete
    Replies
    1. hey where did you set the pagesInRange value ???

      Delete
  63. Thank's very much. It's really very useful and understandable! Nice work!

    ReplyDelete
  64. Thanks a lot..

    It really easy to understand and applicable..

    Nice work! :)

    ReplyDelete
  65. Thanks..Very useful.

    ReplyDelete
  66. Thank you so much! It's very useful!

    ReplyDelete
  67. Thanks for the code. It's very useful. But how can we use this code in search result page. Please help!.

    ReplyDelete
  68. i am getting this error:
    Notice: Undefined variable: db in /var/www/ZendApp/application/controllers/ContsizesController.php on line 17

    Fatal error: Call to a member function fetchAll() on a non-object in /var/www/ZendApp/application/controllers/ContsizesController.php on line 17

    please help me to correct it.Advance Thanks

    ReplyDelete
  69. thank u so much i got the perfect pagination

    ReplyDelete
  70. Thank you for the code brother.

    ReplyDelete
  71. Thanks a lot for solution its work for me in zend framwork

    ReplyDelete