I am trying to update the stock programmaticaly, but I'm having some issues.
What i want to do is before viewing a product on the frontend, check with an external web service to see if the product is in stock or not. and update the stock if it needs to be updated.
i succeeded in updating the stock, but for some reason the result is not shown on the frontend, only when you reload the page.
for example with an out of stock product:
$_product = $this->productRepository->getById($_productId); $stockitem = $this->stockRegistry->getStockItem($_product->getId()); $stockitem->setQty(5); $stockitem->setIsInStock(true) $stockitem->save(); $this->stockRegistry->updateStockItemBySku($_product->getSku(), $stockitem); $_product2 = $this->productRepository->getById($_productId); $_product2->isSalable();
I just can't get this working. But when i refresh the page, the change has been made. So i expect that the product is not being updated correctly. maybe because of cache or indexing, but i tried to reindex by code, and after that get the product from the product repository and still the assailable was the old setting.