Get a list of attribute options from Magento

Chris Forrette picture Chris Forrette · Oct 22, 2010 · Viewed 58.1k times · Source

I've been grabbing attribute options from Magento like so:

<?php

if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}

?>

It's been working fine until I tried to get the options for the built in 'color' attribute -- I got the following error:

PHP Fatal error:  Call to a member function setAttribute() on a non-object in app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php on line 374

It would appear that the getSource() call fails and causes this error. Does anyone know why this happens and how I can get color options out?

Thanks!

Answer

Ivan Chepurnyi picture Ivan Chepurnyi · Nov 10, 2010

It looks like that you initialize attribute by yourself, instead of using Magento attribute initialization process:

Mage::getSingleton('eav/config')
    ->getAttribute($entityType, $attributeCode)

Because since 1.4.x Magento has separate attribute models for catalog and customers model and definition of default source model for catalog_product now is moved from EAV attribute model (Mage_Eav_Model_Entity_Attribute) to the catalog one (Mage_Catalog_Model_Resource_Eav_Attribute).

As a result, some catalog attributes won't work with the EAV attribute model. Particularly those that use Mage_Eav_Model_Entity_Attribute_Source_Table but don't explicitly define it (color, manufacturer, etc.).

The following code snippet should work perfectly on your installation:

$attribute = Mage::getSingleton('eav/config')
    ->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'color');

if ($attribute->usesSource()) {
    $options = $attribute->getSource()->getAllOptions(false);
}

By the way Mage_Eav_Model_Config model has a lot of helpful methods, that can be used in your development, so don't hesitate to look into this model.