Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort Magento collection AFTER load

The Magento collection sorting functions (e.g. Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToSort) work by adding an ORDER BY clause to the SQL select statement. However, there are times when a collection has already been loaded and it is necessary to sort the collection.

It is certainly possible to use the toArray($fields) function and then PHP array sorting functions (either native or user-defined), however this is a little clumsy. It also means that the objects in the collection are converted to "dumb" rows of values without magic getters/setters which can/are be implemented with algorithms, etc.

I'm wondering if there are more elegant/Magento-esque methods of sorting the collection.

Thanks,
Jonathan

like image 418
Jonathan Day Avatar asked Apr 15 '11 06:04

Jonathan Day


People also ask

How do I change the order of items in Magento?

Magento 2 Open Source Edition To change the product sorting, navigate to Catalog > Categories and choose the Store View that you want to change. Then select the needed category, open the Products in Category tab, and edit the Position column. Save the changes.

How do I change the order of categories in a Magento 2?

Reorder Magento 2 Categories Using the Drag and Drop Feature To manage categories in the Magento admin go to Catalog -> Manage Categories. On the left, you will see a category tree. To view all parent categories and subcategories, click 'Expand All'. To rearrange the position of a category, drag it to a new position.

What is sort order in Magento?

The sortOrder property for plugins in Magento 2 determines when to call them (before, after, or around a method), on condition more than one plugin is configured for the same method.


1 Answers

There is no proper way of doing it. But I think it is possible with using of Reflection. You can retrieve $_items property of collection object, sort them and set it back to the collection.

function sortCollection(Varien_Data_Collection $collection, callable $sorter) {
    $collectionReflection = new ReflectionObject($collection);
    $itemsPropertyReflection = $collectionReflection->getProperty('_items');
    $itemsPropertyReflection->setAccessible(true); // Make it accessible

    $collectionItems = $itemsPropertyReflection->getValue($collection);

    usort($collectionItems, $sorter);

    $itemsPropertyReflection->setValue($collection, $collectionItems);

    $itemsPropertyReflection->setAccessible(false); // Return restriction back

    return $collection;
}
like image 125
Ivan Chepurnyi Avatar answered Oct 30 '22 10:10

Ivan Chepurnyi