Magento 1.9 – How to Add a Product to Cart Programmatically

cartcustommagento-1.9

We have a separate promotion rule. For that if customer place an order with certain condition we are giving a free product. For example if a customer placing more than 5 items attracts one same item compliment. From shopping cart price rule discount will be given in terms of amount.

So. I created checkout_cart_product_add_after event and inside the event I am adding below

public function checkoutCartProductAddAfter($observer) {

    $request = $observer->getQuoteItem();

    $sku = $request['sku'];
    $qty = $request['qty'];

    $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
    $quantity = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();

    $addItionalProduct = Mage::getModel('catalog/product')->loadByAttribute('sku', 'MOTO-0');

    $productId = $addItionalProduct->getId();

    try{
        $params = array(
            'product' => $productId,
            'qty' => 2,
        );

        $cart = Mage::getSingleton('checkout/cart');

        $product = new Mage_Catalog_Model_Product();
        $product->load($productId);


        $cart->addProduct($product, $params);
        $cart->save();

        echo 'Done';
    } catch(Exception $e) {
        print_r($e->getMessage());
        die;
    }

}

Reference.

This throws the error message as below:

Fatal error: Maximum function nesting level of '200' reached, aborting!

When I play below logic:

public function checkoutCartProductAddAfter($observer) {
    //$data = $observer->getEvent()->getQuoteItem()->getProduct()->getData();
    $request = $observer->getQuoteItem();

    $sku = $request['sku'];
    $qty = $request['qty'];

    $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
    $quantity = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();

    $addItionalProduct = Mage::getModel('catalog/product')->loadByAttribute('sku', 'MOTO-0');

    $addItionalProductInventory = Mage::getModel('cataloginventory/stock_item')->loadByProduct($addItionalProduct);

    try{
        $cart = Mage::getModel('checkout/cart');
        $cart->init();
        $cart->addProduct($addItionalProduct, array('qty' => 1));
        $cart->save();
    } catch(Exception $e) {
        print_r($e->getMessage());
        die;
    }

}

I am getting below error:

The stock item for Product is not valid.

Can some one guide me on this?

Best Answer

The Fatal error: Maximum function nesting level of '200' reached, aborting! is caused by the fact that you are running into an endless loop.

Your action of $cart->save() is initiating your own routine, which is then action again, saving the cart, and then action your routine again etc....

To block this, you can check the cart items first, and determine if the item being injected is already in cart, and then simply exit the routine if so.

Related Topic