Magento automatically clear old cart items when user logged in using event observer


File: app/ect/modules/Nik_Clearoldcart.xml

<?xml version="1.0"?>
<config>
<modules>
<Nik_Clearoldcart>
<active>true</active>
<codePool>local</codePool>
</Nik_Clearoldcart>
</modules>
</config>

File: app/code/local/Nik/Clearoldcart/etc/config.xml

<?xml version = "1.0" ?>
<config>
<modules>
<Nik_Clearoldcart>
<version>1.0.0</version>
</Nik_Clearoldcart>
</modules>
<global>
<events>
<sales_quote_merge_before><!--calling this event before merging the old cart with newly added cart items while login-->
<observers>
<nik_clearoldcart_observer><!--unique identifier name for our observer-->
<type>singleton</type>
<class>Nik_Clearoldcart_Model_Observer</class><!--Our observer class name-->
<method>loadCustomerQuote</method><!--Method to be called from our observer class-->
</nik_clearoldcart_observer>
</observers>
</sales_quote_merge_before>
</events>
</global>
</config>

File: app/code/local/Nik/Clearoldcart/Model/Observer.php

<?php

class Nik_Clearoldcart_Model_Observer extends Mage_Checkout_Model_Session {

/**
* Clears old cart items after login
*
* @return object currently added cart items
*/
public function loadCustomerQuote() {
$customerQuote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore()->getId())
->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId());

if ($customerQuote->getId() && $this->getQuoteId() != $customerQuote->getId()) {
// Removing old cart items of the customer.
foreach ($customerQuote->getAllItems() as $item) {
$item->isDeleted(true);
if ($item->getHasChildren()) {
foreach ($item->getChildren() as $child) {
$child->isDeleted(true);
}
}
}
$customerQuote->collectTotals()->save();
} else {

$this->getQuote()->getBillingAddress();
$this->getQuote()->getShippingAddress();
$this->getQuote()->setCustomer(Mage::getSingleton('customer/session')->getCustomer())
->setTotalsCollectedFlag(false)
->collectTotals()
->save();
}
return $this;
}

}
?>

In above code we have overridden the Mage_Checkout_Model_Session::loadCustomerQuote() action to avoid merging of old cart items.
Instead of merging the products we have just deleted it!
That’s what we have done!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s