Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "sfpager"

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 
(3 comments)