Code snippets for symfony 1.x

Navigation

Pager for an array of elements v.2

Inspired by this snippet (http://www.symfony-project.com/snippets/snippet/83) here is a version I created that inherits from sfPager. I had a collection of objects (not propel objects) that I needed to iterate through and this did the trick. Note that this is not really optimal because the full array has to be populated with whatever data you are looking at during each request, whereas something like sfPropelPager is smart enough to only fetch/hydrate the objects you are going to need for that particular view.

action:

$myArrayOfThings = array('first', 'second', 'and so on');
$this->pager = new myArrayPager(null, 15);
$this->pager->setResultArray($myArrayOfThings);
$this->pager->setPage($this->getRequestParameter('page',1));
$this->pager->init();

the class:

<?php
class myArrayPager extends sfPager
{
  protected $resultsArray = null;
 
  public function __construct($class = null, $maxPerPage = 10)
  {
    parent::__construct($class, $maxPerPage);
  }
 
  public function init()
  {
    $this->setNbResults(count($this->resultsArray));
 
    if (($this->getPage() == 0 || $this->getMaxPerPage() == 0))
    {
     $this->setLastPage(0);
    }
    else
    {
     $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
    }
  }
 
  public function setResultArray($array)
  {
    $this->resultsArray = $array;
  }
 
  public function getResultArray()
  {
    return $this->resultsArray;
  }
 
  public function retrieveObject($offset) {
    return $this->resultsArray[$offset];
  }
 
  public function getResults()
  {
    return array_slice($this->resultsArray, ($this->getPage() - 1) * $this->getMaxPerPage(), $this->maxPerPage);
  }
 
}
by scott meves on 2007-05-08, tagged pager  sfpager 

Comments on this snippet

gravatar icon
#1 Loïc Vernet on 2007-10-09 at 05:03

Indeed, esay to use , thanks. :)

gravatar icon
#2 Ben Haines on 2008-03-28 at 12:07

Fantastic! Just what I needed. Many thanks.

Remember to clear your cache before using it ;) took me a while to work out why it wouldn't work.

gravatar icon
#3 pedro lima on 2010-07-23 at 04:14

Thank you! Very useful!