cancel
Showing results for 
Search instead for 
Did you mean: 

How to retrieve up-to-date product information after updating stock

How to retrieve up-to-date product information after updating stock

I am trying to add stock quantity dynamically and use the current stock quantity for adding the product to the cart. The stock quantity gets updated successfully, however the ProductRepository keeps returning the outdated stock quantity, therefore I keep getting "out of stock" exception. What's the proper way to achieve this?

 

 

if ($stockItem->getQuantity() - $params["qty"] <= 0) {
        $sourceItem = $this->sourceItemFactory->create();
        $sourceItem->setSourceCode('default');
        $sourceItem->setSku($product->getSku());
        $sourceItem->setQuantity(floatval($params["qty"])+$stockItem->getQuantity()+1);
        $sourceItem->setStatus(1);
        $this->sourceItemsSaveInterface->execute([$sourceItem]);
        // The following part throws an exception (out of stock)
        // SourceItemRepositoryInterface returns the correct stock and quantity information at this point, however $product (even when retrieved from ProductRepository) has the outdated stock information
        $this->quote->addProduct($product, $params);

 

 

1 REPLY 1

Re: How to retrieve up-to-date product information after updating stock

You need to reindex the product before adding and shopping cart, this will help to update the product quantity

protected $indexerRegistry;
public function __construct(
IndexerRegistry $indexerRegistry
) {
$this->indexerRegistry = $indexerRegistry;
}
public function getVersion()
{
.........
$this->indexerRegistry->get('catalog_product_category')->reindexRow($product->getId());
.........
}
If issue solved, Click Kudos & Accept as Solution.
LitCommerce - The Most Simple & Affordable Multi-channel Selling Tool