0

Is there an event for whenever a product goes from In-Stock to Out of Stock and vice-versa.

I basically need to programatically set the value of a custom product attribute depending on the stock status of a product.

Any suggestions?

0

You can use catalog_product_save_after, checkout_submit_all_after ,cataloginventory_stock_revert_products_sale, sales_order_item_cancel(Depending ) and get the stock status. You can even check for that product attribute value is as desired out of stock and that out of stock do nothing else update the attribute value .

Put this events.xml in below path

app\code\YOUR_NAMESPACE\YOURMODULE\etc\

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" />
    </event>
</config>

And put your Productsaveafter.php in below path

app\code\YOUR_NAMESPACE\YOURMODULE\Observer\

<?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct(); // you will get product object and you can check for stock and attribute values here

    }   
}
  • would product_save_after work when an In-stock product eventually sells out and become out of stock? – Fokker May 30 at 7:46
  • @Fokker i have updated events that you can use in answer – Vishwas Bhatnagar May 30 at 10:34

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.