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!
The above code does not work if the resource_model is empty. The following snippet does the job:
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode(Mage_Catalog_Model_Product::ENTITY, 'YOUR_ATTRIBUTE_CODE');
/** @var $attribute Mage_Eav_Model_Entity_Attribute */
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getId())
->setStoreFilter(0, false);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With