Finding it difficult to manage the inventory status in your Magento 2 store? Do you sometimes forget to update the stock availability status after changing the quantity number in the Magento 2 backend? Ever disappointed a visitor with out of stock status which was not the case actually?
I get you!
Developers tend to forget the inventory status after updating the quantity. This results in out of stock status in the frontend although you have updated the stock from the backend.
How about implementing a method that auto change “Stock Availability” on quantity update in Magento 2? In that way, you don’t need to worry about the inventory status. The code below takes care of it!
Steps to Auto Change “Stock Availability” on Quantity Update in Magento 2:
Step 1: Create observer `catalog_product_save_after` in Vendor > Extension > etc > adminhtml > events.xml
<?xml version="1.0"?> <event name="catalog_product_save_after"> <observer name="meetanshi_catalog_product_save_after" instance="Vendor\Extension\Observer\ProductSaveAfter"/> </event>
Step 2: Create observer file
<?php namespace Vendor\Extension\Observer; class ProductSaveAfter implements ObserverInterface { protected $stockRegistry; public function __construct(StockRegistryInterface $stockRegistry) { $this->stockRegistry = $stockRegistry; } public function execute(Observer $observer) { try { $product = $observer->getProduct(); if ($product->getTypeId() != 'configurable') { $sku = $product->getSku(); $stockItem = $this->stockRegistry->getStockItemBySku($sku); $qty = $stockItem->getQty(); $stockItem->setIsInStock((bool)$qty); $this->stockRegistry->updateStockItemBySku($sku, $stockItem); } } catch (\Exception $e) { return $e->getMessage(); } } }
Follow the above steps and you can easily manage the inventory status on quantity change in Magento 2!
Note: The solution works with Magento 2.2.x
Thank you.