Domanda

I have to setup Product 'in stock' and update Quantity programmatically. Here is my code I am trying:

$product->setData('is_in_stock', 1);
$product->setData('qty', 5);
$product->save();
È stato utile?

Soluzione

Can you please try below code? It will save inventory data.

$product->setStockData(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->setQuantityAndStockStatus(['qty' => $stockData, 'is_in_stock' => $stockData]);
$product->save();

Altri suggerimenti

In Magento 2.3 was deprecated change stock directly via setStockData(...) Instead of it, you MUST use this way for updating product stock

  1. Init product stock repository
    public function __construct(
        \Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
    ) {
        $this->productStockRepository = $productStockRepository;
    }

  1. Use Repository for product stock update
    $productStock = $productStockRepository->get($entity->getId());
    $productStock->setStockData(['is_in_stock' => false]);
    $productStockRepository->save($productStock);

In case if you don't use Multi Source Inventory (Magento_InventoryApi extesions), you can update product stock this way:

  1. Init product stock registry
    public function __construct(
        \Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
    ) {
        $this->productStockRepository = $productStockRepository;
    }
  1. Get product stock item and change product stock
    $productStock = $productStockRegistry->getStockItem($entity->getId());
    $productStock = $productStockRepository->get($entity->getId());
    $productStock->setIsInStock(true);
    $productStock->setQty(10);
    $productStock->save();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top