3

I've created custom product attribute which is set on catalog_product_save_before event. Now i want to update value (i have two options of this value) of this attribute for all product, depends on few conditions . How can i do this? The fastest possible method. I can loop through all products and call $product->save(). But i was wondering if there is faster method? Thanks in advance

2

To mass update product attributes, use updateAttributes method, which is faster and better than looping through all the products and save each one of them.

Inject the model class Magento\Catalog\Model\Product\Action in your Observer class and add the code below to update your product attributes

// $productIds is an array of product Ids array(1,2,3,...)
// $attrData is an array of product attributes array('attribute_code1','attribute_code2'...)
// $storeId - you can use the store scope that you wish to update these product attributes

$this->productMassAction->updateAttributes($productIds, $attrData, $storeId);  
4
  • Thank You for your answer, i've already tried this method, but my attribute is drop down and has two options (let say 'yes' and 'no'). I want some products to have this attribute set to 'yes' and other products should have this attribute set to 'no'. I think i can assign one value to all products using this method.
    – SebastianT
    Feb 6 '20 at 8:18
  • @SebastianT you can still use this method for quicker updates. In your case. at first prepare the list of products where you want to set this attribute as 'Yes' or 1 , just use the updateAttributes method to save these products (product ids) with the attribute value as 'yes' and then do the same for the list of products where you want to set this attribute as 'No' or 0.
    – Haijerome
    Feb 6 '20 at 16:29
  • 1
    you are absolutely right :D I was wondering if there is a method which loop through all products and in this loop do some conditions. But your answer is 100% correct and very simple! Thanks.
    – SebastianT
    Feb 7 '20 at 8:36
  • @SebastianT glad it was helpful.
    – Haijerome
    Feb 8 '20 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.