The question:
If have a multiselect attribute and want to set the selection on a product.
$selectedOptions = "red,green,blue";
$product->..... // # what to do?
How can I do that?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
Multiselect attributes can be set as a comma separated list (or also an array) containing the attribute value ids.
So first we have to convert the actual values to Magento’s internal ids.
$attrCode = 'color_base';
$sourceModel = Mage::getModel('catalog/product')->getResource()
->getAttribute($attrCode)->getSource();
$valuesText = explode(',', 'red,green,blue');
$valuesIds = array_map(array($sourceModel, 'getOptionId'), $valuesText);
$product->setData($attrCode, $valuesIds);
$product->save();
Method 2
Modify last line of the above code
$product->save();
with
$product->getResource()->saveAttribute($product, $attrCode);
It works
Method 3
$attrCode = 'color_base';
$sourceModel = Mage::getModel('catalog/product')->getResource()
->getAttribute($attrCode)->getSource();
$valuesText = explode(',', 'red,green,blue');
$valuesIds = array_map(array($sourceModel, 'getOptionId'), $valuesText);
$OptionIds = implode(',', $valuesIds);
$product->setColorBase($attrCode, $OptionIds);
$product->getResource()->saveAttribute($product, 'color_base');
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0