Magento – Customize “apply coupon” action when a particular coupon is applied and then re-update shipping in cart & checkout

coupondiscountmagento-1.9shippingshopping-cart-price-rules

I am running magento ver. 1.9.0.1 in my site.

I want to customize shipping rate when a particular coupon is applied.

How can I do that when "Apply Coupon" button is clicked, if a given coupon is the one, that is applied ?

I never had much encounter with code in price rule section so I am not aware of which controller is executed when "Apply Coupon"(Cart price rule) is clicked.

Best Answer

If you check the HTML of the form you'll see it posts to http://domain.com/checkout/cart/couponPost/.

Magento works with a router that breaks down the URL in [module]/[controller]/[action] which means you know the class and method that handles the post: Mage_Checkout_CartController::couponPostAction.

Now please don't fire up your editor and put the code in that method. The method actually adds the coupon code to the quote and calls collectTotals in class Mage_Sales_Model_Quote which in turn calls _validateCouponCode on line 1376.

I would suggest running your code after that so you're sure the code was valid and applied.

On line 1378 the event sales_quote_collect_totals_after is called. I would use that event to do your magic. The next steps would be:

Which would look like something below.

config.xml

<global>
  [...]
  <events>
    <sales_quote_collect_totals_after>
      <observers>
        <[namespace]_[modulename]_sales_quote_collect_totals_after>
          <type>singleton</type>
          <class>[Module]_[Namespace]_Model_Observer</class>
          <method>salesQuoteCollectTotalsAfter</method>
        </[namespace]_[modulename]_sales_quote_collect_totals_after>
      </observers>
    </sales_quote_collect_totals_after>
  </events>
  [...]
</global>

[Module]/[Namespace]/Model/Observer.php

class [Module]_[Namespace]_Model_Observer
{
   salesQuoteCollectTotalsAfter($observer)
   {
       $quote = $observer->getQuote();
       $couponcode = $quote->getData('coupon_code');
       if ($couponcode == '[your coupon code]') {
          /**
           * Your custom code here
           */
       }

       return $this;
   }
}
Related Topic