Question

I use this code to programmatically update the stock but status remain "out of stock". How to force Magento to set "in stock" when qty change from 0 to 1 or more ?

foreach($importArray as $line){ // pour chaque ligne
  $line = trim($line);
    $line = str_replace('"','',$line);
    $line = explode(';',$line);

  $sku = $line[1];
  $stockValue = $line[2];

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

    if($product->getIdBySku($sku)) {
        $stockItem = $stockRegistry->getStockItem($product->getId());
        $stockItem->setData('qty',$stockValue); //set updated quantity
        $stockRegistry->updateStockItemBySku($sku, $stockItem);
    }

};
Was it helpful?

Solution

Try following code:

$product->setQuantityAndStockStatus(['qty' => $qty, 'is_in_stock' => (bool)$qty]);

OR

$stockItem->setQty($qty);
$stockItem->setIsInStock((bool)$qty);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top