Tuesday, 15 November 2011

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. 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){
 $attributeArray[$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'];
  }
 }
}
Here is a better way to get the multi-select attribute values.
$attributeId = Mage::getResourceModel('eav/entity_attribute')
->getIdByCode('catalog_product','attribute_code_here');

$attribute = Mage::getModel('catalog/resource_eav_attribute')
->load($attributeId);

$attributeOptions = $attribute ->getSource()->getAllOptions();
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)
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();

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Great Read! I am impressed on how you make your article easy to understand. I'll come back for more :D

    Japs Buidon is a Social Media Specialist and belongs to a team of Magento Developer in Florida. For more tutorial and tips you can follow him here -> alwaysopencommerce.com

    ReplyDelete