Question

I'm finding inconsistent documentation on how to update product stock for M2 2.4.1.

Magento\Catalog\Model\Product::setStockData is documented in code to be deprecated and points to Magento\CatalogInventory\Api\Data\StockItemInterface.

StockItemInterface in turn is documented in code to be deprecated and links to pages https://devdocs.magento.com/guides/v2.3/inventory/index.html and https://devdocs.magento.com/guides/v2.3/inventory/catalog-inventory-replacements.html, which are obviously out of date.

Going to the latest page, https://devdocs.magento.com/guides/v2.4/inventory/inventory-api-reference.html, points to Magento\CatalogInventory\Api\StockRepositoryInterface, along with a bunch of other APIs, which is also documented to be deprecated and says "Replaced with Multi Source Inventory".

What is the proper way to programmatically update stock on 2.4?

Était-ce utile?

La solution

In order to use the new API to update stock, add this to the constructor:

public function __construct(
    \Magento\InventoryApi\Api\SourceItemsSaveInterface $sourceItemsSaveInterface,
    \Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory $sourceItemFactory,
) {
    $this->sourceItemsSaveInterface = $sourceItemsSaveInterface;
    $this->sourceItemFactory = $sourceItemFactory;
}

Updating the quantity looks like this:

$sourceItem = $this->sourceItemFactory->create();
$sourceItem->setSourceCode('default');
$sourceItem->setSku($sku);
$sourceItem->setQuantity($qty);
$sourceItem->setStatus(1);
$this->sourceItemsSaveInterface->execute([$sourceItem]);

Source link: https://www.czettner.com/2020/08/24/magento-2-3-update-stock-multi-source.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange
scroll top