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();
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityCan 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();
$product->setStockData(['qty' => $stockData, 'is_in_stock' => $stockData])
is unnecessary. @shashank
Jun 19, 2018 at 4:18
In Magento 2.3 was deprecated change stock directly via setStockData(...) Instead of it, you MUST use this way for updating product stock
public function __construct(
\Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
) {
$this->productStockRepository = $productStockRepository;
}
$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:
public function __construct(
\Magento\InventoryApi\Api\StockRepositoryInterface $productStockRepository
) {
$this->productStockRepository = $productStockRepository;
}
$productStock = $productStockRegistry->getStockItem($entity->getId());
$productStock = $productStockRepository->get($entity->getId());
$productStock->setIsInStock(true);
$productStock->setQty(10);
$productStock->save();
Magento latest version uses the MSI inventory module for managing the inventory. Also providing provisions to create multiple inventory sources. By default, It will use the default source. If you want to set or update product stock then use the below code.
public function __construct(
.....
\Magento\InventoryCatalogApi\Model\SourceItemsProcessorInterface $sourceItemsProcessor
) {
.....
$this->sourceItemsProcessor = $sourceItemsProcessor;
}
public function execute()
{
$data = [
['source_code'=>'default', 'status'=>1, 'quantity'=>50],
];
$this->sourceItemsProcessor->execute(
'your_sku',
$data
);
}
Other solutions are workable but they are deprecated.
So, You may follow the links below. I found these ones helpful.
https://magento.stackexchange.com/questions/325544/proper-way-to-update-stock-in-2-4
https://magento.stackexchange.com/questions/272296/how-to-set-qty-to-product-on-msi-magento-2-3