Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of attribute options from Magento

Tags:

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!

like image 223
Chris Forrette Avatar asked Oct 22 '10 05:10

Chris Forrette


2 Answers

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);
like image 23
Tuong Le Avatar answered Oct 11 '22 15:10

Tuong Le


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.

like image 72
Ivan Chepurnyi Avatar answered Oct 11 '22 16:10

Ivan Chepurnyi