Magento – Pagination and Sorting not working

frontendmagento-1.8paginationsorting

For my custom module I have get product by manufacturer. For template I have copied list.phtml.

On the template file pagination appears but it shows all product instead of selected limit per page. Sorting is not working too.

How can I make it work??

It is my block file:

protected function _getProductCollection() 
{
    if (is_null($this->_productCollection)) {
        $layer = $this->getLayer();
        $brand_id = $this->getRequest()->getParam('id');
        $collection = Mage::getModel('catalog/product')->getCollection();
        $collection->addAttributeToSelect('*');
        $collection->addFieldToFilter(array(
            array('attribute' => 'manufacturer', 'eq' => $brand_id)
        ));
    }

    return $collection;
}

Best Answer

Use below snippet to add pagination and sorting on your custom collection. For every custom collection listing you have to create custom toolbar pager as well.

    $itemsLimit         =   $_GET["limit"] ? $_GET["limit"] : Mage::getStoreConfig('catalog/frontend/grid_per_page');   //Set items to show per page
    $currPage               =   $_GET["p"] ? $_GET["p"] : 1;                //Set current page      
   /*   Set Pagination for Custom Loaded Collection */                              
    $toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
    $toolbar->setCollection($_productCollection);

    /*  Set Pager   */
    $pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
    $pager->setAvailableLimit(array($itemsLimit=>$itemsLimit));
    $pager->setCollection($_productCollection);
    $toolbar->setChild('product_list_toolbar_pager', $pager);
    $toolbar->setData('_current_limit', $itemsLimit);

After this, replace

$this->getToolbarHtml(); by $toolbar->toHtml(); 

to display bottom pager and top sorting toolbar.

For sorting order, do this before collection load:

$_productCollection->addAttributeToSort($_GET["order"], $_GET["dir"]');

I hope this resolves your problem.

Related Topic