How to Programmatically set a Product's Multi-Select Attribute by Labels
-
16-10-2019 - |
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?
Solution
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();
OTHER TIPS
Modify last line of the above code
$product->save();
with
$product->getResource()->saveAttribute($product, $attrCode);
It works
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange