0

Im trying to update the stock of my products programmatically, using this code:

$stockItem = $this->stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($qty);
$this->stockRegistry->updateStockItemBySku($sku, $stockItem);
$this->logger->info($stockItem->getQty())

$stockItem->getQty() logs the right qty amount, however all stock in backend is updated to 0 when I run this loop. Anyone have an idea how this is possible?

  • If you do for 1 product still it shows 0 in backend? – Keyur Shah May 17 at 11:38
  • @KeyurShah Good find! Updating only one product gives the expected result. What could cause this? – Digitaq May 17 at 11:40
  • 1
    It means that you are using singleton of the object , you need to create a new object every time to avoid this situation @Digitaq – Keyur Shah May 17 at 11:43
  • It is possible for you to share full code? @Digitaq – Keyur Shah May 17 at 12:05
  • @KeyurShah I was able to fix the problem! It wasnt that I was using singleton of the object, but the list with stock quanitites that got sent to me got corrupted with false data. Thanks for helping! – Digitaq May 17 at 13:10
0
 $stockItem = $this->stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($qty);
$this->stockRegistry->updateStockItemBySku($sku, $stockItem);
 $stockItem = $this->stockRegistry->getStockItemBySku($sku);
$this->logger->info($stockItem->getQty())
0
    /**
 * @var \Magento\CatalogInventory\Api\StockRegistryInterface
 */
protected $stockRegistry;

public function __construct(StockRegistryInterface $stockRegistry)
{
    $this->stockRegistry = $stockRegistry;
}

/**
* Set the quantity in stock for a product
*
*/
public function applyNewQty($sku, $newQty)
{
    $stockItem = $this->stockRegistry->getStockItemBySku($sku);
    $origQty = $stockItem->getQty();
    $difference = $newQty - $origQty;
    $stockItem->setQtyCorrection($difference);
    $this->stockRegistry->updateStockItemBySku($sku, $stockItem);

    // note that at this point, $stockItem->getQty() is incorrect, so you'll need to reload if you need that value
}

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.