Wow, I’m blown away with how easy it is to get some pagination going with Symfony. In my previous life, I had coded my own custom Pagination class - it would have been easily 100 lines of code. I’ve just implemented some very basic pagination with less than 20 lines of code.

I’m assuming you have created your model objects, and have a basic setup going. Im also doing this in Symfony 1.0. Lets now go ahead and create some basic pagination.

1. Edit your actions.class.php for the module you want to paginate. In my case, I want to create a listing of all companies. For this, I’ll have a executeList action within that class. Here is what it looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class companyActions extends sfActions
{
  ...
  public function executeList(){
    //Get a listing of all companies
    $this->companys = CompanyPeer::doSelect(new Criteria());
 
    //Lets do the pagination for it, firstly define a pager for the Company object. Lets go with 10 results per page
    $pager = new sfPropelPager('Company', 10);
    //Define the criteria, in this case, we won't have any - lets get all companies 
    $pager->setCriteria(new Criteria());
    //Set the first page to 1
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
  }
   ...
}//class

2. Now lets modify your view for listSuccess.php to display what results you are viewing

1
2
//Display a summary of the total companies found, and how many companies there are
echo $pager->getNbResults()." Companies found. Displaying results ".$pager->getFirstIndice()." to ".$pager->getLastIndice();

3. Now lets put in our main code to loop through the paginated results (still in listSucess.php)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
foreach ($pager->getResults() as $company){
    echo $company->getCompanyName();
     //go through and display all you want maybe in a nice table here
     //... 
}
//Now lets display a small navigation bar with arrows for next, previous and page numbers
echo "<br/>";
  <?php if ($pager->haveToPaginate()): ?>
    <?php echo link_to('&laquo;', 'company/list?page='.$pager->getFirstPage()) ?>
    <?php echo link_to('&lt;', 'company/list?page='.$pager->getPreviousPage()) ?>
    <?php $links = $pager->getLinks(); foreach ($links as $page): ?>
      <?php echo ($page == $pager->getPage()) ? $page : link_to($page, 'company/list?page='.$page) ?>
      <?php if ($page != $pager->getCurrentMaxLink()): ?> - <?php endif ?>
    <?php endforeach ?>
    <?php echo link_to('&gt;', 'company/list?page='.$pager->getNextPage()) ?>
    <?php echo link_to('&raquo;', 'company/list?page='.$pager->getLastPage()) ?>
  <?php endif ?>

That’s it! Now have a play with that, and if you are gaim, you could even go and do some Ajax Pagination or get some sorting going.