I have created a grid in Magento and there is a column which is not coming from database instead I have computed it's value from other columns using renderer. lets say custom column in grid is total = columnA from DB - columnB from DB, have to sort the grid based on custom column. I overrided setCollectionToOrder function in my grid., sorted the collection received from prepareCollection function and put the sorted collection in new collection object but I then my grid doesnt show any row , though I can echo the sorted collection and it works fine but no rows come in grid.
protected function _setCollectionOrder($column)
{
$collection = $this->getCollection();
if ($collection) {
switch ($column->getId()) {
case 'total':
$arr = array();
foreach($collection as $item) {
$colA= $item->getcolumnA();
$colB= $item->getcolumnB()
$total= $colA- $colB
$item->setTotal($total);
$arr[$i] = $item; $i++ ;
}
if($column->getDir()=='asc') {
$sorted = usort($arr, array('Grid_Class', '_cmpAscTotal'));
} else {
$sorted = usort($arr, array('Grid_Class', '_cmpDescTotal'));
}
$collection = $this->_tempCollection(); // A blank collection
for($i=0;$i<count($arr);$i++) {
$arr[$i]->setTotal(1);
$collection->addItem($arr[$i]);
}
$this->setCollection($collection);
break;
default:
parent::_setCollectionOrder($column);
break;
}
}
return $this;
}
tempCollection function just gives me a blank collection object (same what prepare collection function gives) _cmpAscTotal is callback function which defines my custom sorting.
protected function _prepareCollection()
{
$collection = Mage::getModel('module/model')->getCollection();
$collection->getSelect()->joinLeft(array('table1' => 'table1'),
'table1.sku = main_table.sku_id',
Array('columnA, columnB, (1) as total')
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
Is there a better way of achieving sorted collection on a custom column, if not what I am doing wrong while modifying the collection that grid becomes empty