1

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.

0

The problem here is that Product Page is cached. So, when you run your php code during the first load, it's actually executed. But when you open your page in the second and subsequent times, the page is already cached, so the code is not executed.

The basic workaround here is to use an AJAX request from the PDP to your custom controller where you should put your logic for getting / setting product's qty.

An example of this approach could found there: https://magento.stackexchange.com/a/128670

2
  • But this is also the case when full page cache is disabled (i think you mean FPC?) so i see that the code is being called by added logging statements. – Jorg van Rossem Oct 14 '18 at 9:24
  • When you call the same AJAX even from the cached page, the result will be different, because you're making a request to the backend controller which will provide the data you need. That's the approach used by Magento itself for retrieving, say, cart items in the minicart. – Nikita Abrashnev Oct 14 '18 at 12:08
0

Have you found a solution to this dilemma? I am facing the same issue, product stock isn't updating until the page is reloaded!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.