A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Zend Framework: How to use Zend_Paginator

Having a “search” functionality in your web application is very essential and for every search comes a “search results” page. It is not hard to create your own search results page with a pagination, but it does take a certain amount of time. But by using Zend_Paginator, you will be able to save time and make your code easier to understand and debug.

Here is a short example on how to create your own search results page with Zend_Paginator.

Before anything else, we start with our search form.

<form method="GET" action="<?=$this->baseUrl()?>/search">
    SEARCH:
    <input name="keyword" type="text"/>
    <input type="submit" value="Search" />
</form>

Next, we have our Controller:

<?php
class SearchController extends Zend_Controller_Action
{
    public function indexAction()
    {
        /**
         * Load model and perform search if $keyword is found in the URL
         */
        $content_model = new Default_Model_Content();
        if($this->_request->getParams('keyword')) {
            $results = $content_model->fetchSearchResults($this->_request->getParams('keyword'));
        }
 
        /**
         * Setup the paginator if $results is set.
         */
        if(isset($results)) {
            $paginator = Zend_Paginator::factory($results);
            $paginator->setItemCountPerPage(20);
            $paginator->setCurrentPageNumber($this->_getParam('page'));
            $this->view->paginator = $paginator;
            /**
             * We will be using $this->view->paginator to loop thru in our view ;-)
             */
 
            Zend_Paginator::setDefaultScrollingStyle('Sliding');
            Zend_View_Helper_PaginationControl::setDefaultViewPartial(
                'query/pagination.phtml' //Take note of this, we will be creating this file
            );
        }
    }

Note: In this tutorial we are using LIKE to compare strings in our MySQL database. The search is very basic and there is no ranking in our results.


The Model
Our model will have 2 files. See below:

<?php
/**
 * First model file.
 * application/models/Content.php
 */
class Default_Model_Content extends Zend_Db_Table
{
    protected $_table;
 
    public function getTable()
    {
        if(null === $this->_table) {
            $this->_table = new Default_Model_DbTable_Content();
        }
        return $this->_table;
    }
 
    public function fetchSearchResults($keyword)
    {
        $result = $this->getTable()->fetchSearchResults($keyword);
        return $result;
    }

And our second model file.

<?php
/**
 * Second model file.
 * application/models/DbTable/Content.php
 */
class Default_Model_DbTable_Orders extends Zend_Db_Table_Abstract
{
    /** Table name */
    protected $_name = 'content';
 
    public function init()
    {
        $this->_db->setFetchMode(Zend_Db::FETCH_OBJ);
    }
 
    public function fetchSearchResults($keyword)
    {
        $sql = 'SELECT * FROM'.$this->_name.
                'WHERE '.
                $this->_db->quoteIdentifier('the_content').' '.
                'LIKE'.
                $this->_db->quote($keyword.'%');
        return $this->_db->fetchAll($sql);
    }



The View
Now that we have our controller and model ready, it is time to setup our view files.

First, create a file called index.phtml in application/views/scripts/search/:

<?php if($this->paginator): ?>
    <table>
        <tr>
            <th>Title</th>
            <th>Content</th>
        </tr>
        <?php foreach($this->paginator AS $key => $row): ?>
            <tr>
                <td><?=$row->title?></td>
                <td><?=$row->the_content?></td>
            </tr>
        <?php endforeach; ?>
    </table>
    <?php echo $this->paginator; ?>
<?php else: ?>
No results.
<?php endif; ?>



The Pagination View File
This is the last step. Now all you have to do is to copy-paste this section of code into a file named: pagination.phtml
Create that file in: application/views/scripts/search/pagination.phtml

<!--
See http://developer.yahoo.com/ypatterns/pattern.php?pattern=searchpagination
-->
 
<?php if ($this->pageCount): ?>
<div class="paginationControl">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
  <a href="<?php echo $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="<?php echo $this->url(array('page' => $page)); ?>">
        <?php echo $page; ?>
    </a> |
  <?php else: ?>
    <span id="current_page"><?php echo $page; ?></span> |
  <?php endif; ?>
<?php endforeach; ?>
 
<!-- Next page link -->
<?php if (isset($this->next)): ?>
  <a href="<?php echo $this->url(array('page' => $this->next)); ?>">
    Next &gt;
  </a>
<?php else: ?>
  <span class="disabled">Next &gt;</span>
<?php endif; ?>
</div>
<?php endif; ?>

Test your search form!

More Reading
Zend_Paginator from the Zend.com manual.

This entry was posted in General and tagged , , , . Bookmark the permalink.

16 Responses to Zend Framework: How to use Zend_Paginator

  1. Pingback: kikblog.luxvii.asia - Zend_Paginator with Search Parameters | Knowledge Is King!

  2. Penton says:

    Hi,

    Do you mind to let me download the zip file of all these codes? Thanks!

  3. Wenbert says:

    Hi Penton,

    I do not have a zip file for all the code in this post. I have tried to make the code as simple as possible for the readers.

    Thanks,
    Wenbert

  4. Penton says:

    Thanks for your swift response. I am having problem passing the keyword to the next page. For example, the initial search will generate the following link:

    http://mydomain.com/search?keyword=silver

    However, the pagination link for next page is:

    http://mydomain.com/search/index/page/2

    Making it return invalid result as the keyword=silver wasn’t within the link. Please advise.

  5. Wenbert says:

    @Penton, you have to explicitly add keyword=silver to the link.
    Try to Zend_Debug::dump($_SERVER). Take a look at $_SERVER['QUERY_STRING'] and see if it will work for you.

  6. Douglas (Brazil) says:

    Very good!!! This is the better example of Zend_Paginator that I see, very easy of understand.

  7. alexander says:

    Very good article indeed.
    But isn’t this going to be an overkill for the db as you are fetching the same amount of data everytime the page changes? Maybe implementing a limit in the fetchSearchResults query might help. I am thinking something like
    $_per_page = 10;
    $_page = $this->_request->getParam(‘page’);
    $_limit = $_per_page * $_page;

    and then of course
    $results = $content_model->fetchSearchResults($this->_request->getParams(‘keyword’),$_limit);
    }

    somethin along those lines.

  8. Sun says:

    How the serch string is attached with the url… so in page 2 there will be no keyword in the url..

  9. Wenbert says:

    @Sun, what you can do is add the keywords in the URL. If the keywords (or let’s say an array), you can use

    serialize()
    //http://www.php.net/manual/en/function.serialize.php

    and then

    base64_encode() 
    //(http://php.net/manual/en/function.base64-encode.php)

    your array.

    In your URL, it would look something like:

    http://mysite.com?page=2&vars=VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

    On the receiving end, you will have to use

    unserialize(base64_decode($_GET['vars']))

    I would probably do this in the pagination.phtml file because this is the part you are building your links on the pagination.

    I hope this helps. I haven’t used Zend Framework in months now.

  10. Rafael says:

    Perfect!

    Thanks from Brazil!

  11. zubzub says:

    every time you display page of results you query for all of the results

    that can’t be good.

  12. sPooKee says:

    Hy,
    nice post, easy to understand, and the best thing is: it works!

    greets

  13. GOKUL says:

    Hi, its good stuff but i have done zend pagination for my zend application in 3 tabs but the whole page is reloading instead of the tab div to show next pagination; Can u pls help me to implement ajax in zend pagination.

  14. pratik says:

    I am beginner in zend framework and i am trying to implement pagination but got failure from last two days.

    From this blog I got at least solution with simple pagination.

    Thanks for it.

  15. matrix says:

    Thanks for your swift response. I am having problem passing the keyword to the next page. For example, the initial search will generate the following link:

    http://mydomain.com/search?keyword=book

    However, the pagination link for next page is:

    http://mydomain.com/search/index/page/2

    Making it return invalid result as the keyword=book wasn’t within the link. Please advise.

  16. Revathi says:

    Nice article very useful. But where is the CSS for this pagination.phtml. Why you haven’t posted it…….?

Leave a Reply to sPooKee Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>