1

I have tried to follow the next solution: Magento 2: Programmatically Updating Inventory

But in Magento 2.3.5 this solution is deprecated. \Magento\CatalogInventory\Api\StockRegistryInterface

Currently what is the solution to update stock?

My code:

public function updateProductStockByData(array $data)
{
    $skuArray = $this->getMapWithSkuKey($data);

    try {
        $productIds = $this->getMapWithProductIdKey($skuArray);
        if (count($productIds)) {
            $searchCriteria = $this->getSearchCriteria($productIds);
            $stockItemCollection = $this->stockItemRepository->getList($searchCriteria);
            if ($stockItemCollection->getTotalCount()) {
                /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
                foreach ($stockItemCollection->getItems() as $stockItem) {
                    $newQty = $this->dataDictionaryWithProductIdKey[$stockItem->getProductId()]['STOCK'];
                    $stockItem->setQty($newQty);
                    if ($stockItem->getQty() == 0) {
                        $stockItem->setIsInStock(false);
                    }
                    $this->stockItemRepository->save($stockItem);
                }
            }
        }
    } catch (\Exception $exception) {
        $this->reportManager->reportNewStockException($exception);
    }
}
1

1 Answer 1

1

Take my answer with a grain of salt. I have a natural tendency to do every CRUD operation using webservices, in the case of Magento, the REST library made available out of the box is awesome. So in order to accomplish the operation you described you can do the following Webservice call:

enter image description here

I've done this in Postman but if you need any further help using Magento webservices let me know ;)

You can find more info on Magento 2 Webservices here:

https://devdocs.magento.com/swagger/

Your Answer

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

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