Zend Framework Pagination

This is a way to have Zend Framework Pagination (Paginator) working so that it remembers the query across mulitiple pages. This seemed like such a simple and obvious task, but the solution is not so obvious. The trick is to test if 'isPost()' then save the query to the session variable. That way when a visitor travels to page two we have the query in the session variable. No URL tricks or other tom foolery.

/IndexController.php

    public function searchAction()
    {
        $value = $this->_request->getPost('query');
 
        // Start a session
        $session = new Zend_Session_Namespace('value');
 
        // If $value is a post then the search has just been submitted.
        if ($this->getRequest()->isPost()) {
            $session->value = $value;
        }
 
        // Get the select from Zend_DB
        $amazon = new Model_Example();
        $result = $amazon->searchExample($session->value);
 
        // Assign Paginator data to view
        $this->view->paginator = $this->_addPaginator($result);
        $this->view->query = $session->value;
        $this->_helper->viewRenderer('list');
    }
 
    private function _addPaginator($select)
    {
        $page = $this->_getParam('page', 1);
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage(self::ItemCountPerPage)
                  ->setCurrentPageNumber($page)
                  ->setPageRange(5);
        return $paginator;
    }

/layout/scripts/layout.phtml

<div id="search"><form action="/index/search" method="POST"><input type="text" name="query" id="query" value="<?php echo $this->query; ?>"><input type="submit" name="Submit" value="Submit"></form></div>

/views/scripts/index/list.phtml

<?php if($this->paginator): ?>
<div><?php echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?></div>
 
<?php foreach($this->paginator as $item): ?>
<!-- list your item data -->
<?php endforeach; ?>
 
<div><?php echo $this->paginationControl($this->paginator, 'Sliding', 'pagination.phtml'); ?></div>
<?php endif; ?>

Credit:
http://www.zfforums.com/zend-framework-components-13/databases-20/proble...

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <drupal5>, <drupal6>, <javascript>, <php>, <sql>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options