Event Observer – Observe Product Quantity Changes Only

event-observer

I have some complicated cart validation logic that I need to check every time the qty of a product in the cart changes. I don't need to check the logic when a product is added or removed entirely, just when the qty changes.

I am observing sales_quote_item_qty_set_after but that fires every time you load the cart, add a product, remove a product, etc. I would assume that I would want to grab the qty of all products in the cart to start with and then compare that with the items in the sales_quote_item_qty_set_after event. I should then be able to identify the product that started with a qty > 0, ended with a qty > 0, and a delta <> 0. I'm having trouble figuring out the logic for that.

Thanks,

Best Answer

OK, here's the function that triggers the event in 1.9.0.2

public function setQty($qty)
{
    $qty = $this->_prepareQty($qty);
    $oldQty = $this->_getData('qty');
    $this->setData('qty', $qty);

    Mage::dispatchEvent('sales_quote_item_qty_set_after', array('item' => $this));

    if ($this->getQuote() && $this->getQuote()->getIgnoreOldQty()) {
        return $this;
    }
    if ($this->getUseOldQty()) {
        $this->setData('qty', $oldQty);
    }

    return $this;
}

So, the observer is only being passed the current state of the item. If it's triggering everytime you load the cart then maybe this won't work, but you can use $item->dataHasChangedFor('qty') to see if it's changed since the object was loaded, and $item->getOrigQty() to get what it was when it was loaded.