Magento Adding Pagination To Custom Collection

If you are like me, you are working with collections a lot and more times than not you will be faced with the need to produce a pagination for your collections on the frontend.

Magento already has a pagination toolbar if you take not of the catalog category pages  that house products. So how can we tap into this with our own collections (be it products or other types)?

Simple, first assuming you have your collection vandalized:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();

Then we can toss this collection into a core page/html_pager block by doing the follow:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();
echo $this->getLayout()->createBlock('page/html_pager', 'some_block_name_want')->setCollection($custom_collection)->toHtml();

$this will works both in frontend phtml files, and controllers or models, but is just the basics.
Vola, this will product a basic pagination query string functionality to your collections.

Please note there are additional way to do this would be to abstract out the pager block to a variable before passing the collection to give you the opportunity to set additional options:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();
$pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
$pager->setAvailableLimit(array(15=>15));
$pager->setCollection($custom_collection);
echo $pager;

See how I’ve set the available limit the pager block will allow.

Lastly, the sort-by feature you have seem on the catalog category product listing page’s is not part of the pagination tool, nor is it a global functionality piece. To better learn about sort-by feature, I suggest you study /template/catalog/product/list/toolbar.phtml to see how it uses backend functionality to tap into the $this->getRequest()->getParam(‘some_name’,0); to alter the collections based on the option a user selects.

Thanks!

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus

One Response to “Magento Adding Pagination To Custom Collection”

  1. Jason says:

    Great, but I do not see how this actually creates the pagination links on the page. What does your code look like in custom.pager?

Leave a Reply