8

I need to detect whenever the inventory level of a product changes. As there is cataloginventory_stock_item_save_after in magento 1.x wanto to implemet same in magento 2.1

<event name="cataloginventory_stock_item_save_after">
    <observer name="cataloginventorysave" instance="Vendor\Module\Observer\Cataloginventorysave" />
</event>

Then created observer "Cataloginventorysave.php" in which I want to access

$stockItem = $observer->getEvent()->getItem();

But event name cataloginventory_stock_item_save_after is not found in magento 2 event list. How will I achieve it.

8

This is a bug.

Basically those events are dispatched dynamically in Magento\Framework\Model\AbstractModel in the afterSave() method:

public function afterSave()
{
    $this->cleanModelCache();
    $this->_eventManager->dispatch('model_save_after', ['object' => $this]);
    $this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $this]);
    $this->_eventManager->dispatch($this->_eventPrefix . '_save_after', $this->_getEventData());
    $this->updateStoredData();
    return $this;
}

As you can see, this code use $this->_eventPrefix to generate the name of the event.

But the problem with Magento\CatalogInventory\Model\Stock\Item is that this variable is not declared properly:

protected $eventPrefix = 'cataloginventory_stock_item';

See the problem ? It's missing an underscore, it should be:

protected $_eventPrefix = 'cataloginventory_stock_item';

I suggest you create a bug report here so the team is aware of it: https://github.com/magento/magento2/issues

After digging it, it seems like someone found the bug before us: https://github.com/magento/magento2/issues/4857

Please note that the PR has already been merged to the develop branch

5
  • thank you. it worked.. but now I want product id so I tried : $stockItem = $observer->getEvent()->getItem(); – SPK Sep 16 '16 at 6:09
  • 1
    $id = $stockItem->getProductId(); I got error: PHP Fatal error: Call to a member function getProductId() on null – SPK Sep 16 '16 at 6:09
  • @SPK It requires a fix to the $_eventObject attribute name. Without this fix the event always passes the event data as 'Object' instead of the expected 'Stock' and 'Item'. – Geethika Antony Jul 14 '17 at 10:02
  • is that event dispatched by an order or api? – Antonio Pedicini Jul 29 '17 at 9:02
  • In this event any idea how to get the previous qty in Magento 1 getOrigData('qty') can be used for it.But it is not working in 2. – Geethika Antony Aug 10 '17 at 4:28

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.