0

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?

asked Jan 17 at 10:18

1 Answer 1

0

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/

answered Jan 20 at 9:35
1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.