Zend Framework: How to use Zend_Paginator

Posted on: Jun 22, 2009 by wenbert

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.


Subscribe to comments Comment | Trackback |
Post Tags: , , ,

Browse Timeline


Comments ( 10 )

[...] click here and here for the complete post. AKPC_IDS += “412,”;Popularity: unranked [?]SHARETHIS.addEntry({ title: [...]

kikblog.luxvii.asia - Zend_Paginator with Search Parameters | Knowledge Is King! added these pithy words on Jul 22 09 at 10:55 AM

Hi,

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

Penton added these pithy words on Jul 22 09 at 11:23 AM

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

Wenbert added these pithy words on Jul 22 09 at 1:41 PM

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.

Penton added these pithy words on Jul 22 09 at 4:07 PM

@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.

Wenbert added these pithy words on Jul 22 09 at 6:16 PM

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

Douglas (Brazil) added these pithy words on Jul 24 09 at 3:14 AM

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.

alexander added these pithy words on Sep 01 09 at 6:08 AM

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

Sun added these pithy words on Jul 23 10 at 8:10 PM

@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.

Wenbert added these pithy words on Jul 23 10 at 11:26 PM

Perfect!

Thanks from Brazil!

Rafael added these pithy words on Aug 25 10 at 5:25 AM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!