I want to update automatically Product Attribute on Base of Stock status in Product, I have created few attributes with Yes/NO. Now I want when the product will become out of stock that attribute will update automatically NO.

If Product is

In-stock = Product Attribute is Yes

Out-of-stock = Product Attribute is No

Can we do this?

enter image description here

1 Answer 1


Using the event: cataloginventory_stock_item_save_after You can create your own observer where you can check if the stock_status changed to "out of stock" and set your attributes accordingly (All of this if you added the attribute's inside the Magento stock table)

public function execute(\Magento\Framework\Event\Observer $observer)
    $stockItem = $observer->getEvent()->getItem();
    $origStockStatus = $stockItem->getOrigData('is_in_stock');
    $newStockStatus = $stockItem->getData('is_in_stock');
    if(($origStockStatus != $newStockStatus) && $newStockStatus === 0){
         $stockItem->setData('custom_stock_attribute', 0);


That's only if your attribute is a stock attribute, if that's a product attribute then you can still use this observer but you'll have to load the product from the stock item:

$_productId = $stockItem->getProductId();  // you will get product ID 
$_product = $this->productRepository->getById($productId)

Or you can also save only the attribute, if you fear an infinite loop

$product->setData('custom_stock_attribute', $custom_stock_attribute);
$product->getResource()->saveAttribute($product, 'custom_stock_attribute');
  • 1
    This is a very bad suggestion. Saving the stock item in an after event will cause an infinite loop.
    – puntable
    Apr 7, 2022 at 13:22
  • i've edited the answer May 25, 2022 at 22:55

Your Answer

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

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