- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-04-2021
05:33 AM
01-04-2021
05:33 AM
Magento 2 cannot change saleable quantity from observer
Hi,
I am new on Magento 2 and I am trying to update Product quantity when a user views the product, using an external API. In Magento 1.9 I succeeded in creating a custom observer. In magento 2.4 although I can change the quantity from stock in real time, the saleable quantity changes after the page refresh.
events.xml
<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="catalog_controller_product_view"> <observer name="mymodule__update_product_observer" instance="HubIT\FarmakonConnect\Observer\UpdateProduct" /> </event> </config>
Observer.php
class UpdateProduct implements ObserverInterface { protected $scopeConfig; protected $getSalableQuantityDataBySku; protected $stockRegistry; public function __construct(ScopeConfigInterface $scopeConfig, GetSalableQuantityDataBySku $getSalableQuantityDataBySku, StockRegistryInterface $stockRegistry) { // Observer initialization code... $this->scopeConfig = $scopeConfig; $this->stockRegistry = $stockRegistry; $this->getSalableQuantityDataBySku = $getSalableQuantityDataBySku; } public function execute(Observer $observer) { $product = $observer->getEvent()->getProduct(); $sku = $product->getSku(); $id = $product->getId(); $qty = $this->productBalance($sku); //Get data from Api $stockItem = $product->getExtensionAttributes()->getStockItem(); $origQty = $stockItem->getQty(); $stockItem->setQty($qty); $stockItem->setIsInStock((bool)$qty); $this->stockRegistry->updateStockItemBySku($sku, $stockItem); echo 'test'.$qty.' '.$origQty.' '.$product->isSaleable().'<br>'; $salable = $this->getSalableQuantityDataBySku->execute($sku); echo json_encode($salable); } }
How can I achieve that?
Labels:
1 REPLY 1
- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-18-2021
12:20 PM
01-18-2021
12:20 PM
Re: Magento 2 cannot change saleable quantity from observer
No one knows how to inform the magento for quantity changes?
Is there any other way to achieve what I want?