Magento : Add pagination to a custom entity listing

In this article I'll discuss about how to you implement a pagination on your custom entity listing. Also In this blog post, we will see how to and toolbar to any custom collection. In last week I had a requirement to add paging facility in our custom module’s collection. Normally, magento provides paging in products collection. But this time, it is something different. To satisfy that requirement, I had searched the web and found the best solution which I want to discuss here.

So now follow the under given steps:

First of all, integrate the Mage_Page_Block_Html_Pager through your block :

class Your_Module_Block_Entityname_List extends Mage_Core_Block_Template
{

  protected function _construct()
  {
      parent::_construct();

    // We get our collection through our model
    $this->_entities = Mage::getModel('your_module/entityname')->getCollection()
        ->setOrder('created_at');

    // Instantiate a new Pager block
    $pager = new Mage_Page_Block_Html_Pager();

    // We set our limit (here an integer store in configuration). 
    // /!\ The limit must be set before the collection
    $pager
      ->setLimit((int)Mage::getStoreConfig('your_module/entityname/pagination'))
      ->setCollection($this->_entities);

    // Add our Pager block to our current list block
    $this->setChild('pager', $pager);
  }
}

You can set the paging limits to the block: $pager->setAvailableLimit(array(1=>1, 7=>7, 128=>128)).

After that You just need to include the call in your template (.phtml) file :

<div class="your_module_entities">
  <?php foreach($this->_entities as $entity) : ?>

    <div class="entity">
      <h2><?php echo $entity->getAttribute1(); ?></h2>
      <p><?php echo $entity->getAttribute2(); ?></p>
    </div>

  <?php endforeach; ?>
</div>

<?php echo $this->getChildHtml('pager'); ?>

That's it. :)