0

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

0

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);
         $stockItem->save();
    }

}   

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)
$_product->setData('custom_stock_attribute',0);
$_product->save();
0

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.