The following code is a observer function when a customer apply a coupon code which will be saved in a table
public function trackcode($observer) {
$event = $observer->getEvent();
$eventName = $event->getName();
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->beginTransaction();
$__fields = array();
$quote = $event->getQuote();
$item = $observer->getEvent()->getItem();
//$item = $event->getItem();
$action = strtolower(Mage::app()->getFrontController()->getAction()->getFullActionName());
if ($action == 'checkout_cart_couponpost') { //if on the apply coupon action
if ($quote->getCouponCode()) {
$coupon_code = $quote->getCouponCode();
$__fields['quote_item_id'] = $item->getId();
$__fields['coupon_code'] = $coupon_code;
$__fields['sku'] = $item->getSku();
$__fields['customer_email'] = $this->getCustomerEmail();
$connection->insert('name_trackcode', $__fields);
$connection->commit();
}
}
}
config.xml
<global>
<events>
<salesrule_validator_process>
<observers>
<name_trackcode>
<type>model</type>
<class>Name__Trackcode_Model_Observer</class>
<method>trackcode</method>
</name__trackcode>
</observers>
</salesrule_validator_process>
</events>
<global>
But at the onestepcheckout page, at the shipping method step, i pressed "continue", there will be a
invalid shipping method
alert message.
It seems that the events not only run at the time the coupon apply, but also view cart page, view checkout page.
Anyone know what are the problems?
1 Answer 1
If you allow us lets refactor that code.
public function trackcode(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$eventName = $event->getName();
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$__fields = array();
$quote = $event->getQuote();
$item = $observer->getEvent()->getItem();
//$item = $event->getItem();
$action = strtolower(Mage::app()->getFrontController()->getAction()->getFullActionName());
if ($action != 'checkout_cart_couponpost') {
return;
}
if (!$quote->getCouponCode()) {
return;
}
$connection->beginTransaction();
try {
$coupon_code = $quote->getCouponCode();
$__fields['quote_item_id'] = $item->getId();
$__fields['coupon_code'] = $coupon_code;
$__fields['sku'] = $item->getSku();
$__fields['customer_email'] = $this->getCustomerEmail();
$connection->insert('name_trackcode', $__fields);
$connection->commit();
}
catch(Exception $e) {
$connection->rollBack();
}
}
We're not sure if it's related to your issue, but it's good to always commit an open transaction.