Magento: Getting product attributes values and labels
I have found that it is very useful to be able to get attributes from the system and use them in places other than a products category page. I always forget the exact syntax to use so, this is going to be my unofficial cheat sheet.
This is how to get a drop down lists options. I don’t think it will work for a mulit-select attribute. I stick the value/label pairs into an array to use how I please.
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_id');
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
$attrubuteArray[$option['value']] = $option['label'];
}
I had a trickier time getting values for a multi-select attribute. I don’t think that this is the best method, but it is one that worked for me. First the multi-select attribute must be set to be used in the advanced search. You can set this in the manage attributes area.
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray=array();
foreach($attributes as $a){
if($a->getAttributeCode() == 'desired_attribute_code'){
foreach($a->getSource()->getAllOptions(false) as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
}
If you only need to retrieve a value for a product you can try this way
//Referenced from /app/code/core/Mage/Eav/Model/Config/php @ line 443
$_product->getResource()->getAttribute('club_type')->getFrontend()->getValue($_product)
I added this code snip it below to possibly answer a question that was posted. The code below will get an attribure collection. Set {entityType} to 4 to get attributes for products. You can remove the “setCodeFilters” line if you want to get all the attributes. To get anything really useful you will probably need to get the resulting attribute ids and do someting with them, like use them in a filter for the products collection or something.
//
$attributesInfo = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter({entityType})
->setCodeFilter($attributes)
->addSetInfo()
->getData();
Entity Type Id’s
$entityType is an integer id for what type of entity the attribute is associated to. If you look at the “eav_attribute” table you will see that each attribute has an entity_type_id.
1 = Customer Entity
2 = Shipping Entity (I believe)
3 = Category Entity
4 = Product Entity
The Following code was added to answer a question in the replies:
To make a product attribute avaliable when getting a product collection(such as on a category page or search results page) you can add some code the a config.xml file that instructs Magento to load allways the attribute when a product collection is loaded.
How to add an attribute to be loaded whenever a product collection is loaded:
This can go in any config.xml file. I would recommend putting it in a custom module rather than one from the core code. Just replace “attribute_name” with the attribute code of the attribute you are trying to add.
<frontend> <product> <collection> <attributes> <attribute_name/> </attributes> </collection> </product> </frontend>

35 Responses to “ Magento: Getting product attributes values and labels ”
April 22nd, 2009 at 5:26 am
You are my hero today!
Thanks a lot!
June 18th, 2009 at 10:48 am
wow! the 2nd method works fine!!
I use this to check if attribute exits too:
if (!$id = $eav_entity_setup->getAttribute($entity_type_id, $code, ‘attribute_id’)) {
return false;
}
thanks!
July 28th, 2009 at 12:35 am
Oh! Thank you ! You save my time.
August 30th, 2009 at 5:48 pm
Thank you! I have been trying to find this code for the last few days.
Nick
September 7th, 2009 at 12:18 pm
Thanks, do you have any idea how to get attributes by attribute_id which only relate to existing products in DB.
I’ll try to display it as filters (so if no products have assigned attribute, attribute not display).
September 7th, 2009 at 8:14 pm
Added reference to code that gets a collection of attributes.
September 17th, 2009 at 12:36 am
thanks dude
September 21st, 2009 at 5:15 pm
It would be helpful if you could post a further description of what $entityType is (from the last example) and why 4 is the value to use for products.
September 22nd, 2009 at 7:08 am
$entityType is an integer id for what type of entity the attribute is associated to. If you look at the “eav_attribute” table you will see that each attribute has an entity_type_id.
1 = Customer Entity
2 = Shipping Entity (I believe)
3 = Category Entity
4 = Product Entity
and so on. THese four ids are the ones that you will commonly use.
November 12th, 2009 at 10:44 am
thanks very much!
I used this: $_product->getResource()->getAttribute(‘club_type’)->getFrontend()->getValue($_product)
but for total noobs (like myself) it is worth to mention that you need to add “echo” in front of the line to actually display the value of the attribute: so in your code you will have:
getResource()->getAttribute(‘name_of_the_attribute’)->getFrontend()->getValue($_product) ?>
hope this helps someone totally lost,
Kamil
November 17th, 2009 at 10:09 am
[...] compléter cet article, voici un lien assez intéressant permettant d’afficher tous les attributs automatiquement, etc. [...]
November 25th, 2009 at 9:39 pm
For the multi-select, if you’re within a Mage_Catalog_Block_Product_View template (ie view.phtml) then you don’t need the advanced search visibility to be set or referenced, this works as well:
$attributes = $_product->getAttributes();
$attributeArray=array();
foreach($attributes as $a){
if($a->getAttributeCode() == 'your_code_here'){
foreach($a->getSource()->getAllOptions(false) as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
}
December 29th, 2009 at 9:19 am
Hi
thanks for this, which is pretty clear, but I dont get anything when I code this:
public function test_ProductData_DefaultProductSize_ShouldBeT1()
{
// Actors
$_product;
$optionCode ="size";
$expectedValue = "T1";
$actualValue = "QUELLE EST CETTE TAILLE";
$productId = "4b38dffad30c6";
// Activities
$_product= null;
$_product = new Mage_Catalog_Model_Product();
$_product = Mage::getModel('catalog/product')->load($productId);
$actualValue = $_product->getResource()
->getAttribute($optionCode)
->getFrontend()
->getValue($_product);
// Asserts
$this->assertEquals($expectedValue, $actualValue, "ASSERT FAILURE: attribute $optionCode is wrong.");
}
any idea of what I could have missed?
December 29th, 2009 at 9:21 am
I get this display:
There was 1 failure:
1) Moz_Product_ProductTestAttributes::test_ProductData_DefaultProductSize_ShouldBeT1
ASSERT FAILURE: attribute size is wrong.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-T1
+No
December 29th, 2009 at 11:01 am
@J: I believe you are loading the product incorrectly. After you load the product, does “$_product” have an ID “$_product->getId()”?
December 30th, 2009 at 3:43 am
Thanks Mike D,
I rewrote the get of the product as :
public static function GetProductFromSku($skuId)
{
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku',$skuId)
->load();
if (0 === count($products)) {
throw new Exception("Error: Product $skuId not found");
}
$product = null;
foreach($products as $p) {
$product = $p;
break;
}
if(null === $product) {
throw new Exception("Error: Product $skuId not in result collection");
}
return $product;
}
and then my test is:
public function test_ProductData_DefaultProductSize_ShouldBeT1()
{
// Actors
$_product= null;
$optionCode ="size";
$expectedValue = "T1";
$actualValue = "QUELLE EST CETTE TAILLE";
$productId = "cdn0001";
// Activities
$_product = new Mage_Catalog_Model_Product();
$_product = common_ProductData::GetProductFromSku($productId);//Mage::getModel('catalog/product')->load($productId);
$actualValue = $_product->getResource()->getAttribute($optionCode)->getFrontend()->getValue($_product);
// Asserts
$this->assertNotNull($_product->getId(), "ASSERT FAILURE: Product id should be set !");
$this->assertTrue($_product->getId() > 0, "ASSERT FAILURE: Product id is ".$_product->getId());
$this->assertEquals("1", $_product['stock_item']['is_in_stock'], "ASSERT FAILURE: Product should be In Stock");
$this->assertEquals($expectedValue, $actualValue, "ASSERT FAILURE: attribute '$optionCode' is wrong.");
}
But the result is still:
There was 1 failure:
1) Moz_Product_ProductTestAttributes::test_ProductData_DefaultProductSize_ShouldBeT1
ASSERT FAILURE: attribute 'size' is wrong.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-T1
+No
C:\svn\moz\trunk\tests\integration\Moz\Product\ProductTestAttributes.php:27
FAILURES!
Tests: 1, Assertions: 5, Failures: 1.
When I parse the attributes with a foreach ($_product->getAttributes() as $attribute)
I can see the “Size”, but it is the label. How to get the value for the $_product ?
January 18th, 2010 at 2:31 am
I’m trying to retrieve attributes name (multilanguage) in the catalog list (when the products are listed in categories), is it possible using this method?
Because “$attribute->getSource()->getAllOptions(true, true)” returns me an empty array of this type:
“Array ( [0] => Array ( [label] => [value] => ) )”
Am I doing something wrong?
January 18th, 2010 at 8:01 am
What type of attribute is “multilanguage”?
1. I am assuming you created it?
2. Is it a text field, drop-down, …?
Are you just trying to display it for each product on the product list?
One way to do this would be to add that attribute to a config file so it always loads when Magento grabs the product collection. I have added sample code to the end of the post that demonstrates this.
January 19th, 2010 at 12:15 am
Here is the solution to get attribute label for multilanguage site:
$attributeLabel = $_product->getResource()->getAttribute(‘YOUR_ATTRIBUTE_CODE’)->getFrontendLabel();
$translationArray = Mage::app()->getTranslator()->getResource()->getTranslationArray();
echo $translationArray["Mage_Catalog::".$attributeLabel];
Hope this helps.
January 19th, 2010 at 11:02 pm
hay any one help me to list out all options and its values of particular product…
January 20th, 2010 at 8:26 am
@Bhavesh Dave: Are you trying to print all options for a particular attribute for a product or all attributes for a product?
if $product is your product then you list attributes by
$product->getAttributeName();
To see all the attributes available you can do print_r($product);
Does this help?
February 10th, 2010 at 9:25 am
THANK YOU!
You saved me a lot of time!
Now i can go home
March 31st, 2010 at 5:01 am
Nice Posts, but I have a different problem, I would like to add a foreign key to the product table. i.e. I wanted to filter the product according to the administrator who added the product from the administrator’s panel. i.e. I want to keep track of the products according to administrator’s role and permission. Is it possible to do so. If yes, how? Please respond. Thanx.
March 31st, 2010 at 6:46 am
@tuppi Sau: What you want to do sounds reasonable. You would need to create a module that adds the nessary attributes to the product then create an observer or override the methods for product create/update. If you are a beginner you might want to pay someone to build this.
Here are a few articles that should get you started.
For installing custom attributes with a module
To add the new attributes to the product grid you will more than likely need to override the block and template files for this.
April 27th, 2010 at 1:44 am
Is it possible to get all (non core) attributes in the magento shop? I need this to create attribute sets programatically.
April 27th, 2010 at 6:53 am
I don’t believe there is a method that will do exactly that. I am not sure why you would need to do that. If you are creating an attribute set then you should know what attributes you want to add to it so just use addAttributeToFilter(), for each attribute you want. Or explain what you are trying to do a little better.
May 26th, 2010 at 2:11 am
Hello,
I’m looking for a method to show all possible attributes and their values for some product, even those, which are not in stock. I have to show possible sizes and colors to the customer..
Any ideas how to add filtering by product ID to “get all attributes/values”?
Thanks.
May 26th, 2010 at 6:36 am
This might not be the easiest way, but what if you make an array of attributes with the key of the array being the attribute_code and the value being what type of attribute it is(select, multi-select, text field, ect.) Then do a foreach loop with the array and check to see if the current product has that attribute then if it does have the attribute, check to see which type of output it has(select, multi-select, text field, ect.) and use the appropriate code from the example above to retrieve the values.
I cant remember if there is a method that will just get all the attributes for a product.
May 26th, 2010 at 6:56 am
Thank you, Mike.
I also found another variant, looks like it works:
$possibleAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);June 5th, 2010 at 1:44 pm
Thanks, it worked and now can show the attribute option value in product listing.
June 29th, 2010 at 2:27 am
Thanks Mike, with your help now I see custom attributes on my landing pages!
July 12th, 2010 at 3:51 pm
[...] http://www.sharpdotinc.com/mdost/2009/04/06/magento-getting-product-attributes-values-and-labels/ [...]
August 2nd, 2010 at 6:36 am
Thanks!!!
September 4th, 2010 at 12:17 pm
HI i have a Problem getting the Options of an Multiselect Attribute… I created the multiselect Attribute in the Adminpanel with two options. Now i tried this:
$attribute = Mage::getModel(‘eav/entity_attribute’);
$attribute->loadByCode(‘catalog_product’, “products_author_unique”);
$options = $attribute->getSource()->getAllOptions(false);
but “$attribute->getSource()” throws an error:
Fatal error: Call to a member function setAttribute() on a non-object in C:\xampp\htdocs\Magento\app\code\core\Mage\Eav\Model\Entity\Attribute\Abstract.php on line 374
a dump of my $attribute looks like this:
Mage_Eav_Model_Entity_Attribute Object
(
[_eventPrefix:protected] => eav_entity_attribute
[_eventObject:protected] => attribute
[_cacheTag:protected] => EAV_ATTRIBUTE
[_name:protected] =>
[_entity:protected] =>
[_backend:protected] =>
[_frontend:protected] =>
[_source:protected] =>
[_attributeIdCache:protected] => Array
(
)
[_dataTable:protected] =>
[_resourceName:protected] => eav/entity_attribute
[_resource:protected] =>
[_resourceCollectionName:protected] => eav/entity_attribute_collection
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[attribute_id] => 577
[entity_type_id] => 4
[attribute_code] => products_author_unique
[attribute_model] =>
[backend_model] => eav/entity_attribute_backend_array
[backend_type] => varchar
[backend_table] =>
[frontend_model] =>
[frontend_input] => multiselect
[frontend_label] => products_author_unique
[frontend_class] =>
[source_model] =>
[is_required] => 0
[is_user_defined] => 1
[default_value] => 6
[is_unique] => 0
[note] =>
[frontend_input_renderer] =>
[is_global] => 0
[is_visible] => 1
[is_searchable] => 1
[is_filterable] => 1
[is_comparable] => 1
[is_visible_on_front] => 0
[is_html_allowed_on_front] => 1
[is_used_for_price_rules] => 0
[is_filterable_in_search] => 1
[used_in_product_listing] => 1
[used_for_sort_by] => 0
[is_configurable] => 0
[apply_to] =>
[is_visible_in_advanced_search] => 1
[position] => 0
[is_wysiwyg_enabled] => 0
[is_used_for_promo_rules] => 0
)
[_hasDataChanges:protected] => 1
[_origData:protected] =>
[_idFieldName:protected] => attribute_id
[_isDeleted:protected] =>
)
September 5th, 2010 at 11:29 am
@Peter: Doesn’t look like you followed the directions for a MultiSelect Attribute.
Read Paragraph 3.
I had a trickier time getting values for a multi-select attribute. I don’t….