Skip to main content
1 of 3
Anil
  • 420
  • 3
  • 17

Magento product quantity update programatically if product status is desable

We want update product quantity programatically. If product status is Enable then quantity update properlly. But which product status is Disable quantity not update in it. We create one custom module for it. Any one help me for sort out this.

Here is my module Block/Index/index.php file code.

public function updateStock($productId,$productQty)
{
    $product = $this->productFactory->create()->load($productId);
    
    if($product->getStatus() == 2){ // 2 => Disable , 1 => Enable
        
        $product->setStatus(1);
        
        if($product->getStatus() == 1){
            $product->setStockData([
                //'use_config_manage_stock' => 0, //'Use config settings' checkbox
                //'manage_stock' => 1, //manage product stock
                'is_in_stock' => 1, //Stock Availability
                'qty' => $productQty 
            ]);
                
            $product->setQuantityAndStockStatus([
                'qty' => $productQty,
                'is_in_stock' => 1
            ]); 
        }
        
        $product->setStatus(2);
        
        try {
            $product->save(); 
            echo 'Quantity update of SKU => '.$product->getSku().'<br/>'; 
        } catch (Exception $e) {
            echo $e->getException();
        }
        
    }else{
    
        $product->setStockData([
            //'use_config_manage_stock' => 0, //'Use config settings' checkbox
            //'manage_stock' => 1, //manage product stock
            'is_in_stock' => 1,
            'qty' => $productQty
        ]);
            
        $product->setQuantityAndStockStatus([
            'qty' => $productQty,
            'is_in_stock' => 1
        ]); 
        
        try {
            $product->save(); 
            echo 'Quantity update of SKU => '.$product->getSku().'<br/>'; 
        } catch (Exception $e) {
            echo $e->getException();
        }
    }
Anil
  • 420
  • 3
  • 17