2

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

1

You can use below sample code

$product->setStockData(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->setQuantityAndStockStatus(['qty' => $yourQty, 'is_in_stock' => 1]);
$product->save();
  • Where is product id ? How to set product it for update qty ? – Chirag Parmar Sep 12 at 6:17
  • in your question you already added product id and load the product my code was only to update stock data – Narayan Jat Sep 12 at 6:21
  • This is works for me. Thanks @Narayan. I gave my working code bellow. – Chirag Parmar Sep 12 at 6:38
1
<?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.

0

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!!!

0

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

  • Display error. Notice: Undefined variable: objectManager in /var/www/html/m229/t8.php and Fatal error: Uncaught Error: Call to a member function create() on null in /var/www/html/m229/t8.php:7 Stack trace: #0 {main} thrown in /var/www/html/m229/t8.php on line 7 – Chirag Parmar Sep 12 at 6:29
  • Try now, I have initialize object manager – Shoaib Munir Sep 12 at 6:35
  • Your script is fine, just replace the qty assigning part. If this still not working, then I will update full script. Please let me know if you are facing any error – Shoaib Munir Sep 12 at 6:36

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.