Getting dropdown attribute value when using addAttributeToSelect
-
11-12-2019 - |
Question
When loading a collection how can I get the attribute value text (and not just the option number) when its a dropdown attribute.
Example:
$collection = Mage::getResourceModel('catalog/product');
$collection->addAttributeToSelect('color'); // color is a dropdown attribute
When using this code the option id's are displaying for color
such as: 123, 117 etc. and not the text values (like: red, green etc.)
Usually we iterate through each product and get the text for the attribute but since this is being used in the Catalog->Manage products page I'm looking for an alternate solution.
Solution
I assume that you are firstly using Mage_Catalog_Model_Resource_Product_Collection
and not simply the resource as stated in your question.
Now I am also assuming that you are looping through the results of your collection.
foreach($collection as $product) {}
Once you have the product object you can call the function getAttributeText
and specify the attribute code. This will load the attribute get the source and then the option text based on the attribute data assigned to the product.
public function getAttributeText($attributeCode)
{
return $this->getResource()
->getAttribute($attributeCode)
->getSource()
->getOptionText($this->getData($attributeCode));
}
So if you are looping through your collection you need to simply call:
foreach ($collection as $product) {
$color_value = $product->getAttributeText('color');
}
OTHER TIPS
Try adding "_value" after the attribute name like this:
$collection = Mage::getResourceModel('catalog/product');
$collection->addAttributeToSelect('color_value'); // color is a dropdown attribute
If you are using flat tables for products, you can look in the catalog_product_flat_1 database table to see the available attributes, I believe.
Do you need to sort by the values? If not, you can select all attribute options as a $colors
hash with one(!) query and then display them as $colors[$product->getColor()]
Probably it's faster than select each value in the loop or make extra joins, but does not work for collection sorting :(