Friday, November 6, 2009

BUG: Entity attribute option collection order

I confirm with everyone that Magento 1.3.2 (latest version at the moment) has a bug. This is not a real bug and will not cause any problem to your magento site, but it will give you some unexpected result when you do some custom modification to Magento.

The bug happens when you retrieve a option list of a custom attribute by the order that you have defined in admin. The code should look like following:

$_options = Mage::getResourceModel('eav/entity_attribute_option_collection')
  ->setStoreFilter(0)
  ->setAttributeFilter($attribute_id)
  ->setPositionOrder('asc')
  ->load();

foreach ($_option as $option)
{
  // doing stuff
}

We use setPositionOrder method here, because we want to the query result follows the order that we define in Magento Backend. You can check the method in app\code\core\Mage\Eav\Model\Mysql4\Entity\Attribute\Option\Collection.php.

But due to a bug in the collection class, you will always get the result in alphabet order. So right now, the correct way to retrieve the collection in position order is to use the follow code:

$_options = Mage::getResourceModel('eav/entity_attribute_option_collection')
  ->setPositionOrder('asc')
  ->setStoreFilter(0)
  ->setAttributeFilter($attribute_id)
  ->load();

It's easy to understand because when you call the setStoreFilter first, Magento will set the order by value for the query, that's why you always get the result in value order. But if you call the setPositionOrder first, the default value order is put behind the position order, and it works.

I will report this bug to Magento and hope they will fix it in the next version.

1 comment: