How to set selected value in multiselect attribute
-
16-10-2019 - |
Question
How to set selected value in multiselect attribute progmatically. I tried this one but it doesn't work for me.
How to Programmatically set a Product's Multi-Select Attribute by Labels
the code on the link above doesn't stop from loading
$productObj = Mage::getModel('catalog/product')->load($product->getId());
$productObj->setData('filter_category','51,52');
$productObj->save();
the code above is invoke after catalog_product_save_after
Solution
Since you want to do this in the action catalog_product_save_after
you could simple update the individual product attribute and not the complete product, thus stopping the infinite loop problem.
$attrCode = 'your_attribute';
$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->getResource()->saveAttribute($product, $attrCode);
OTHER TIPS
As others have mentioned, the problem is that you go into an infinite loop if you save the product again in the save_after
event.
- you should use the
save_before
event - Don't
load()
the product again,$product
already contains all data - Don't
save()
as the data you set on$product
will be saved after the event has finished
So the code for your new observer looks like this:
public function setFilterCategoryBeforeSave(Varien_Event_Observer $observer)
{
$observer->getProduct()->setData('filter_category','51,52');
}
That's all.
You can filter multiple select using finset. Below is a small example of how filter it
$collection = $this->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->addAttributeToFilter($attribute,array('finset'=>array_search($selection,$valueId)))
->setPageSize($limit)
->load();
Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
here $selection is the value of multiple select attribute to be filtered