Symfony Tips & Tricks IV: Generalized & Ajax Pagination

OK, so we’ve got the basics. But once you start implementing this into some projects or several places into one project you’ll notice that there will be a lot of copying. And once you want to change the layout or the structure you have to adapt a lot of code. I decided to first refactor a bit so that all the code is nicely in one place. Aside from that I’ll introduce very simple ajax to load the pages.

Setup

For this example I’m going to use my module ‘offers’ with an index and a _list partial

This could later have any custom setting for this pager, either standard pager config or customized methods.

Reusable Template

Ok not much has changed yet – you might still be wondering why you’re going through the trouble of reading (or doing) this. Now comes the interesting part. We’ll add a generalized template to our /apps/frontend/templates/ directory:

And of course to be able to use it we’ll need to modify our pager class// /apps/frontend/lib/myDoctrinePager.class.php
public function __construct(Doctrine_Query $query, $ajax_url, $max_pages=null)
{
// ..
$this->setTemplate("global/paging");
}

The only thing that might be a little confusing here is how to render a partial from your model. I use the same approach as sfAction does: loading the partial helper through sfContext and simply printing the partial.

The last change is we’ll need to modify our partial to use the render() method.

render(); ?>

Adding ajax

OK, so far we’ve only refactored paging to make it reusable on different parts of your application. You might not even have needed all that. It might be you are skipping here. Well just for that I’ve kept adding the ajax very very easy. I’ll use jQuery.

First we’ll add some javascript to our index template. You might want to change how you’ve named jquery (or if you don’t have it yet, download it from the jquery website and place it under /web/js/jquery.js)

$offers, 'pager' => $pager)) ?>

So with that out of the way we’ll need to use the new loadPage(page) function.haveToPaginate()): ?>