Skip to content

Instantly share code, notes, and snippets.

@luckyduck
Created January 8, 2018 13:49
Show Gist options
  • Save luckyduck/7563710e6a590310b846812975447034 to your computer and use it in GitHub Desktop.
Save luckyduck/7563710e6a590310b846812975447034 to your computer and use it in GitHub Desktop.
public function couponPostAction()
{
/**
* No reason continue with empty shopping cart
*/
if (!$this->_getCart()->getQuote()->getItemsCount()) {
$this->_goBack();
return;
}
$couponCode = (string) $this->getRequest()->getParam('coupon_code');
if ($this->getRequest()->getParam('remove') == 1) {
$couponCode = '';
}
$oldCouponCode = $this->_getQuote()->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
$this->_goBack();
return;
}
try {
$codeLength = strlen($couponCode);
$isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
->collectTotals()
->save();
if ($codeLength) {
if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
$this->_getSession()->addSuccess(
$this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode))
);
$this->_getSession()->setCartCouponCode(strtolower($couponCode));
} else {
$this->_getSession()->addError(
$this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode))
);
}
} else {
$this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
}
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Cannot apply the coupon code.'));
Mage::logException($e);
}
$this->_goBack();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment