I want to sort catalog products by name in natural order. In order to achieve it i created a custom module and overwrote Mage_Catalog_Block_Product_List_Toolbar.
public function setCollection($collection)
{
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
// we need to set pagination only if passed value integer and more that 0
$limit = (int)$this->getLimit();
if ($limit) {
$this->_collection->setPageSize($limit);
}
if ($this->getCurrentOrder() == 'name') {
//i'm assigning the custom sorted collection
$this->_collection = $this->_naturalsort($this->_collection);
//printing the collection to check whether it's in proper order
$this->_test($this->_collection);
}else if ($this->getCurrentOrder()) {
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
}
return $this;
}
protected function _naturalsort($collection){
$prodarr = $collection->exportToArray();
usort($prodarr, function($a, $b) {
return strnatcmp($a['name'], $b['name']);
});
$collectionsorted = new Varien_Data_Collection();
foreach($prodarr as $item)
{
$varienObject = new Varien_Object();
$varienObject->setData($item);
$collectionsorted->addItem($varienObject);
}
return $collectionsorted;
}
protected function _test($collection){
foreach($collection as $item2)
{
Mage::log($item2['name']);
}
}
When logging the collection using my _test method the products are in correct order. Still it doesn't affect the frontend view. The frontend displays a non sorted collection. What am i doing wrong?