Tuesday, February 14, 2017

Update product stock information programmatically in Magento 2

Update product stock information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

### Reference:
### http://magento.stackexchange.com/questions/96519/magento-2-programmatically-updating-inventory
$sku = 'WWW1';
$stockQty = 55;

$productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');
$stockRegistry = $objectManager->create('\Magento\CatalogInventory\Api\StockRegistryInterface');

### Load product by SKU
$product = $productRepository->get($sku);

### Load stock item
$stockItem = $stockRegistry->getStockItem($product->getId());

$stockItem->setQty($stockQty);
#$stockItem->setData('qty', $stockQty);

#$stockItem->setData('manage_stock', $stockData['manage_stock']);
#$stockItem->setData('is_in_stock', $stockData['is_in_stock']);
#$stockItem->setData('use_config_notify_stock_qty', 1);

print_r($stockItem->getData());

$stockRegistry->updateStockItemBySku($sku, $stockItem);

No comments: