28Jan/111

Show Values of Multi-Select Attribute in Magento

In Magento, multi-select attributes are a great way to create a very detailed attribute for products. However, if you want to display them on the product page outside of the default Attribute table, it can be a bit trickier. Using this snippet of code, you can show a comma separated list on the product page from your multi-select attribute.

When would that be useful? We recently built a Magento store for a company that sells handguns online. These handguns cannot be shipped to some states (we call these "restricted states"). Instead of having the client enter that information into the Description field of every single product, we created a multi-select attribute and then wrote out it's values on each product page.

Here is how it works:

NOTES:
I use restrictedstates in this example but it will work fine for any multi-select attribute.
I am assuming you want to show this info after the description text.

1. Create a multi-select attribute
2. Magento 1.4 open the file template/catalog/product/view/description.phtml
3. After the description is echoed out, add this code:


<?php
  $multiSelectArray = $this->getProduct()->getAttributeText('restrictedstates');
  $lastItem = end($multiSelectArray);

  foreach($multiSelectArray as $multiSelectItem){
    echo $multiSelectItem;
    if($multiSelectItem != $lastItem) echo ", ";
  }
?>

So in our case, the selected values for this multi-select attribute could have been CA, MA and MD. This example would output:

CA, MA, MD

If you wanted to separate them with dashes, just change the ", " in the last line of code to " - "

For pages other than the product view page:

If you need this information on any other page, you can use the following code:

$attribute = Mage::getModel('catalog/product')->getAttribute('catalog_product', 'restrictedstates');
$options = $attribute->getSource()->getAllOptions(true, true);
$lastItem = end($options);

foreach($options as $option) {
	// $option['label'] is the value
	// $option['value'] is the ID of the option value in the database

	echo $option['label'];
	if($option != $lastItem) echo ", ";
}

Any questions or problems, ask in the comments and i'll be happy to try and help!

About John Webber

John is the founder of MagThemes.com and has been working with Magento since version 0.9
Comments (1) Trackbacks (0)
  1. thanks so much for this…one problem… when i only have one attribute selected it doesnt show them…any solution for this?


Leave a comment


No trackbacks yet.