2

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);
    }

};

1 Answer 1

4

Try following code:

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

OR

$stockItem->setQty($qty);
$stockItem->setIsInStock((bool)$qty);
2
  • thanks a lot, the second one works. just need to change the $qty by $stockValue in my script.
    – cap340
    Dec 21, 2017 at 4:27
  • @urbansurfers - Happy to help. Keep helping :)
    – Pratik Oza
    Dec 26, 2017 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.