3

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.

2

3 Answers 3

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');
}
0

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.

3
  • This will only work assuming Flat Product tables are enabled.
    – lukefowell
    Commented Jul 16, 2014 at 21:33
  • Oh, right. I see. backend stuff. Ignore this answer. Commented Jul 16, 2014 at 22:14
  • Even with flat tables enabled it doesn't work, this is driving me nuts. Commented Nov 17, 2016 at 18:53
0

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 :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.