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.
-
This might be related: magento.stackexchange.com/questions/10212/…mbalparda– mbalparda2014年07月16日 20:06:08 +00:00Commented Jul 16, 2014 at 20:06
-
This might help. stackoverflow.com/a/8164964/925083Eli Y– Eli Y2014年07月17日 05:28:46 +00:00Commented Jul 17, 2014 at 5:28
3 Answers 3
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');
}
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.
-
This will only work assuming Flat Product tables are enabled.lukefowell– lukefowell2014年07月16日 21:33:27 +00:00Commented Jul 16, 2014 at 21:33
-
Oh, right. I see. backend stuff. Ignore this answer.The Phil Lee– The Phil Lee2014年07月16日 22:14:50 +00:00Commented Jul 16, 2014 at 22:14
-
Even with flat tables enabled it doesn't work, this is driving me nuts.Matt Cosentino– Matt Cosentino2016年11月17日 18:53:23 +00:00Commented Nov 17, 2016 at 18:53
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 :(