I have created a product attribute in Magento2 which is of type multiple select. Right now it is empty for all products and has no options created. With my php code I am trying to add a random value to each product via foreach code. This is the code:
foreach($simple_collection as $simple_product){
$randomNumber = rand($minValue, $maxValue);
$simple_product->setdiscountprice($randomNumber);
$productResource->saveAttribute($simple_product, 'discountprice');
echo 'discountprice aggiornato per: '.$simple_product->getSku().'<br/>';
}
Why is it not working and not adding any kind of value to the multiple select attribute of the product?
1 Answer 1
If this is a multiple select attribute, you have to insert option code instead of the value itself.
To get a option id from label, you can use the following code to refer:
public function getAttributeLabel($attr, $value){
$attribute = $this->config->getAttribute(ProductModel::ENTITY, $attr);
return $attribute->getSource()->getOptionText($value);
}
Where $this->config is from Magento\Eav\Model\Config. You can use dependency injection to inject into your custom class.
More Ref: https://webkul.com/blog/get-option-label-from-option-id-and-attribute-code-magento-2/
-
check this once may it helps magento.stackexchange.com/questions/323549/…Sanjay Jethva– Sanjay Jethva2025年01月22日 04:05:54 +00:00Commented Jan 22 at 4:05
Explore related questions
See similar questions with these tags.