1

I am trying to ensure that customers carts are not saved upon logout.

I have the following Observer method that fires on load_customer_quote_before:

public function deleteQuote(Varien_Event_Observer $observer) {
    $customerQuote = Mage::getModel('sales/quote')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId());
    $customerQuote->removeAllItems();
    $customerQuote->save();
}

This is resulting in some bizarre behavior, however. If the customer had items in their cart in last logout, and I do a customer login with items in the cart, things work fine.

However, if the customer had items in their cart and I do a customer login with NO items in the cart, I see at the links at the top of the page "My Cart (X items)" where X is equal to the number of items that were in the customer's cart. This link (which I've cropped from a publicly available site):

My Cart

This isn't just a passing thing, this incorrect number remains no matter where else I go on the site...

...until I actually click on the "My Cart" or "Checkout" link. Then, reality catches up it and it realized that I killed the old quote and displays the correct number of items with either no items or a couple of them depending on if I had added any items to the cart after logging in. It's almost as if there is a count somewhere that doesn't update unless it has to.

This is really bizarre. How can I fix this number?

1 Answer 1

0

After a considerable amount of digging, I finally got to the bottom of this.

Tracing the number all the way down, you eventually get to Mage_Sales_Model_Quote, where as it turns out the counts or quantities of the items you have in the quote is not calculated automatically based on what's in the quote, but is part of the quote's data. Thus, if you clear the cart without updating the count/qty as well, the two will go out of sync.

Thankfully, there is a built-in method to handle recalculation of those numbers - Mage_Sales_Model_Quote::collectTotals(). So all you have to do is add a single line to the observer...

public function deleteQuote(Varien_Event_Observer $observer) {
    $customerQuote = Mage::getModel('sales/quote')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId());
    $customerQuote->removeAllItems();
    $customerQuote->collectTotals(); // Ensure count/qty is updated.
    $customerQuote->save();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.