Magento – Auto Save In Stock if Quantity Greater Than 0

adminproduct

I am working on a store with thousands of products. I have noticed that when product Quantity is zero (or manually turned to Zero) the Stock Availability goes 'Out of Stock' however when we update the product Quantity to number greater then zero like 10,15 or 200 the 'Stock Availability' stays 'Out of Stock' unless and until manually changed to 'In Stock' so that the product appears on fronted.

I want the 'Stock Availability' to Auto turned to 'In Stock' as we update the Quantity to number greater then Zero. The Quantity in my case gets its values from the store inventory software we don't change it manually.

Event used cataloginventory_stock_item_save_commit_after

Any help and tips will be appreciated.

public function autoinstockproduct($observer) { 



   $product = $observer->getProduct();
    $stockData = $product->getStockData();

    if ( $product && $stockData['qty'] > 0) {
        $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getEntityId()); // Load the stock for this product
        $stock->setData('is_in_stock', 1); // Set the Product to InStock                               
        $stock->save(); // Save
    }
}

But this code is not working

Reference question

Best Answer

The event that you need to use in this case is catalog_product_prepare_save and change your observer method like this :

public function autoinstockproduct($observer) 
{
    $product   = $observer->getProduct();
    $stockData = $product->getStockData();

    //make sure stock qty is greater than zero.
    if (isset(stockData['qty']) && $stockData['qty'] > 0) {
        $product->setStockData['is_in_stock'] = 1; //update to instock
    }
}

This is more better solution than the accepted solution from your reference question because of following reasons :

  1. It listens to more specific event which will be fired for catalog product edit save action from admin side.
  2. It removes stock model loading and additional saving.

Other than this, you need to exactly follow what @quaisersatti suggests in his answer in the referenced thread in order to properly configure your observer in your module.