Question

I want to update product qty and change Stock Status as in stock by programmatically by product id. I dont want to insert new product, but I want only update existing product by its id. Any one know how to do it ? I tried following code but not getting result.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();  
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
//$productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface');
//echo 'VERSION ==> '.$productMetadata->getVersion();

$product_id = 1;
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');


//$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$product->setQty(100);
$product->save();

Edit : i want to run in a root directory and simple one php file. I want to run as

localhost/m229/updateproduct.php

Was it helpful?

Solution

You can use below sample code

$product->setStockData(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->setQuantityAndStockStatus(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->save();

OTHER TIPS

You can use below code snippet in your script to update the stock data and status of the product.

$stockData = [
        'use_config_manage_stock' => 0, // checkbox for 'Use config settings' 
        'manage_stock' => 1, // manage stock
        'min_sale_qty' => 1, // Shopping Cart Minimum Qty Allowed 
        'max_sale_qty' => 2, // Shopping Cart Maximum Qty Allowed
        'is_in_stock' => 1, // Stock Availability of product
        'qty' => 100 // qty of product
        ];

$product->setStockData($stockData);
$product->setQuantityAndStockStatus($stockData);
$product->save();

Also, you can use the below code in your helper or block class in your custom module to update product stock status.

protected $_product;

/**
 * @var Magento\CatalogInventory\Api\StockStateInterface 
 */
protected $_stockStateInterface;

/**
 * @var Magento\CatalogInventory\Api\StockRegistryInterface 
 */
protected $_stockRegistry;

/**
* @param Magento\Framework\App\Helper\Context $context
* @param Magento\Catalog\Model\Product $product
* @param Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
* @param Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
*/
public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Catalog\Model\Product $product,
    \Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, 
) {
    $this->_product = $product;
    $this->_stockStateInterface = $stockStateInterface;
    $this->_stockRegistry = $stockRegistry;
    parent::__construct($context);
}

/**
 * For Update stock of product
 * @param int $productId which stock you want to update
 * @param array $stockData your updated data
 * @return void 
*/
public function updateProductStock($productId,$stockData) {
    $product=$this->_product->load($productId); //load product which you want to update stock
    $stockItem=$this->_stockRegistry->getStockItem($item['product_id']); // load stock of that product
    $stockItem->setData('is_in_stock',$stockData['is_in_stock']); //set updated data as your requirement
    $stockItem->setData('qty',$stockData['qty']); //set updated quantity 
    $stockItem->setData('manage_stock',$stockData['manage_stock']);
    $stockItem->setData('use_config_notify_stock_qty',1);
    $stockItem->save(); //save stock of item
    $product->save(); //  also save product
}

Hope it helps!!!

Note: use of Object manager is not recommended, but since you are using custom script, I will also give you answer using object manager

Try this code:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();  
$productRepository = $objectManager->create('\Magento\Catalog\Model\ProductRepository');
$stockRegistry = $objectManager->create('\Magento\CatalogInventory\Api\StockRegistryInterface');

$id = 1;
$product = $productRepository->getById($id);
$stockItem = $stockRegistry->getStockItemBySku($product->getSku());
$stockItem->setQty(100);
$stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

Hope this will work for you

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface');
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();  
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
//$productMetadata = $objectManager->get('Magento\Framework\App\ProductMetadataInterface');
//echo 'VERSION ==> '.$productMetadata->getVersion();

$product_id = 1;
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');


//$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
//$product->setQty(100);
$yourQty = 100;
$product->setStockData(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->setQuantityAndStockStatus(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->save();

This is works for me. i copied some code from Narayan's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top