Magento checkout_cart_product_add_before and get number of products added

lleto picture lleto · Nov 26, 2012 · Viewed 9.4k times · Source

I created the event checkout_cart_product_add_before: http://markshust.com/2012/08/27/create-checkout_cart_product_add_before-observer-magento

Hoever when I do this the getQuoteItem() seems to be unavailable, so I cannot get to the number of products added to cart. When I use the _after method I can use:

public function checkStock2($observer) {
  Mage::log("Check stock before");
  $request = $observer->getQuoteItem();
  Mage::log("q in order = " .$request['qty'] ."");
}

However when I am before I cannot reach the getQuoteItem as it is not there yet. Is there a way I could get the number of products the user is trying to add to the cart?

Thanks!

Answer

Jscti picture Jscti · Nov 26, 2012

If you implemented the linked observer, you're missing the information you need. You have to add the request in your dispatchEvent, in order to check what the user chose :

public function addProduct($productInfo, $requestInfo=null)
    {
        $product = $this->_getProduct($productInfo);
        $request = $this->_getProductRequest($requestInfo);
        Mage::dispatchEvent('checkout_cart_product_add_before', array(
             'product' => $product,
              'request' => $request
        ));

        return parent::addProduct($productInfo, $requestInfo);
    }

Then you'll be able to retrieve the user quantity in your observer with :

$observer->getEvent()->getRequest()->getQty();

the ->getRequest() method refers to a magic getter for the "request" parameter of your dispatchEvent.