Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento custom collection breaks pagination

I created a collection by adding items to a Varien_Data_Collection collection object.

$collection = new Varien_Data_Collection();
  foreach($array_of_products as $productId){
    $collection->addItem(Mage::getModel('catalog/product')->load($productId));
}

However when this object is passed on to Magento pager block as given below, it breaks the pagination in my custom page.

$pager = $this->getLayout()->createBlock('page/html_pager', 'retailerfe.analysis.pager')
            ->setCollection($collection);

P.S I have never had problems with collections fetched from model collections like Mage::getModel('module/modelname')->getCollection(). It is just collections created by adding items to a Varien_Data_Collection Object.

like image 786
Adheesh Avatar asked Jan 20 '12 06:01

Adheesh


2 Answers

The pager is calling setPageSize on your collection which - if you trace it - is only used by getLastPageNumber. This means the pager can show the number of pages accurately but that's it. It is Varien_Data_Collection_Db that actually does anything with the current page number and size by rendering them as a LIMIT clause for SQL.

To create a collection that respects the page criteria you will have to create a descendant to the class. For ideas look at the source of Varien_Data_Collection_Filesystem and how it implements loadData.


I've just re-read your question and realised you can do this:

$collection = Mage::getModel('catalog/product')->getCollection()
            ->addIdFilter($array_of_products);

This collection will page quite happily.

like image 102
clockworkgeek Avatar answered Sep 21 '22 12:09

clockworkgeek


I just doubt on(may be i am wrong):

$collection->addItem(Mage::getModel('catalog/product')->load($productId));

which should be like this:

$collection->addItem(Mage::getModel('catalog/product')->load($productId)->getData());

Let me know if that works for you. Thanks

EDIT:
Finally i figured it out. Here is how you should do it:

<?php
$collection = new Varien_Data_Collection();
foreach($array_of_products as $productId){
    $product = Mage::getModel('catalog/product')->load($productId); 
    $_rowObject = new Varien_Object();
    $_rowObject->setData($product->getData());
    $collection->addItem($_rowObject);
}
like image 27
2 revs Avatar answered Sep 18 '22 12:09

2 revs