You can typically just use addAttributeToSort() to sort any collection retrieved through the getCollection() function. If you’re retrieving your collection through a resource model or another means these functions may not be available for use and will result in an error. This can lead to wondering why you can’t complete something as simple as sorting a collection within Magento and most likely the following error:

Fatal error: Call to undefined method Collection::addAttributeToSort()

You can still sort this collection but you must firstly get the MySQL select statement and manually order it using commands provided in Magento.

This can be done by running two functions on your collection. Replacing the field_name with the field you wish to sort by and then proceeded by the desired order (DESC – Descending, ASC – Ascending)

Here is an example where I am sorting an attribute set collection by their names.

Dave Macaulay
Dave Macaulay
I'm an enthusiastic, slightly eccentric Magento developer who bores with the idea of another basic brief.
  • Isolde

    Hi Dave,

    Thankyou for this bit of code! I couldn’t get my dropdown with attribute sets to sort and this fixed it!

    • daavem

      No problem man! Glad I helped you around one of the confusing parts of Magento.