3
votes

I am new to Magento, but I thought I had a grasp on it until today. Here is my problem.

I am writing a new Observer to add a coupon to the cart on page load. The coupon code is passed in the URL and I desire the code to be passable through ANY working URL.

For example: http://magento/?coupon=MYCOUPON

I am catching on the event "controller_front_init_routers" to capture the coupon code.

I have the observer working, but if I already have an item in the cart and I pass a coupon code my cart appears empty, here is how I am adding the coupon:

    public function applyCoupon($observer){
        $coupon_code = $observer->getEvent()->getData('front')->getRequest()->getParam('coupon');
        if(!empty($coupon_code)){
            Mage::getSingleton('checkout/session')->setData('coupon_code', $coupon_code);
            Mage::getSingleton('checkout/cart')->getQuote()->setCouponCode($coupon_code)->save();

            Mage::log('Coupon Code: '. $coupon_code);
        }
    }

It seems that anytime I call Mage::getSingleton('checkout/session')->anything() I lose the session for the cart.

I thought maybe I simply needed to fetch the current cart ID and load it, but I can't seem to find a way to do that either.

Has any one had experience in this, maybe has a solution?

1

1 Answers

2
votes

The problem is in event, that you are observing. Because Magento session wasn't initialized at that moment, so cookie has different name, than core one.

Use controller_action_predispatch for setting up some session data from request.