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

};
4

Try following code:

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

OR

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

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.