Magento: Issue with getAttributeText() in 1.4?

I haven’t been able to take the time to test this more in-depth, and on different versions yet – fyi. I have only tested this on

If you need to output the value(s) of an dropdown or multiselect attribute for a product, you use getAttributeText(‘attribute_code’). This works perfectly fine on these attributes as long as only 1 option is selected. In this case, it will return a string. However, if you have a multiselect attribute with more than 1 optino selected, it then returns an array.

While this seems like it would make sense, it doesn’t bid well for multiselect attributes, as you have to account in your code to check if it is returning a string or an array, and display it accordingly. Instead of a nice clean attribute call like:

echo $_product->getAttributeText('attribute_code') ;

You have to do something like this instead for all multiselect attributes:

$_attribute = $_product->getAttributeText('attribute_code');
echo (is_array($_attribute)) ? implode(', ', $_attribute) : $_attribute;

This just doesn’t seem like a solid way to have to do this… Either getAttributeText() should always return a string or an array, or there should be a different method to use for multiselect attributes – something that will always return an array. Or – am I missing something here? Is there a better way to do this?

This entry was posted in Magento. Bookmark the permalink.

2 Responses to Magento: Issue with getAttributeText() in 1.4?

  1. Vinai says:

    The Attribute Source Model is responsible for taking care of the implode. For Magento Mage_Eav_Model_Entity_Attribute_Source_Table handles that case (see getOptionText(). So if you use a different source model you need to make sure getOptionText works with multiple values.

  2. Ben says:

    Might do to create a helper that performs the type test, that way you can just
    echo $helper->getAttributeText($product, 'attribute_code');
    and add it to any project you like.