How to pager array items in Magento

The Mage class Mage_Page_Block_Html_Pager is handy to pager collection items, but it is designed to work with a collection derived from Mage_Core_Model_Mysql4_Collection_Abstract.

Now I run into a situation to pager arbitrary array items. The array items are pre-built and not loaded via a resource model, so the pager lost a clue how to control which items to display. (Which makes me think – Magento is powerful, but not so powerful without the help of mysql – Magento collection functionality rely heavily on mysql operation – it is a bit off topic.)

So I need to tell the pager how to load the array after array items are loaded already. The following is my solution class.

<?php
class Qian_Msdk_Model_PagerableCollection extends Varien_Data_Collection {

/***
* load only current page items
*/
public function load($printQuery = false, $logQuery = false) {
if ($this->isLoaded()) {
return $this;
}
$this->loadForPager();
$this->_setIsLoaded();
return $this;
}

public function loadForPager() {
if (!$this->getPageSize()) {  //not pagerized
return $this;
}
$items = array();
$currentPage = $this->getCurPage();
$i = 0;
foreach ($this->_items as $item) {
if ($i < ($currentPage-1) * $this->getPageSize()) {
$i++;
}
elseif ($i >= $currentPage * $this->getPageSize()) {
break;
}
else {
$items[] = $item;
$i++;
}
}
$this->_items = $items;
return $this;
}

/***
* get the size of collection before pagerize
*/
public function getSize()
{
if (is_null($this->_totalRecords)) {
$this->_totalRecords = count($this->_items);
}
return intval($this->_totalRecords);
}

}

3 comments

  1. You can use the array_slice method to paginate the collection

    $items = array_slice($items, ($currentPage – 1) * $this->getPageSize(), $this->getPageSize(), true);

Leave a comment

Your email address will not be published. Required fields are marked *