Magento – How to clear the compare list

comparemagento-1.7

I need that, when the user goes to the compare list page it will reset so if he navigates to the products again he will have to choose different products for the list.

How can I do this?

Best Answer

You can use the code that Magento uses in the clearAction() of the product compare controller and addapt it a little:

$items = Mage::getResourceModel('catalog/product_compare_item_collection');
    if (Mage::getSingleton('customer/session')->isLoggedIn()) {
        $items->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId());
    } elseif ($this->_customerId) {
        $items->setCustomerId($this->_customerId);
    } else {
        $items->setVisitorId(Mage::getSingleton('log/visitor')->getId());
    }

/** @var $session Mage_Catalog_Model_Session */
$session = Mage::getSingleton('catalog/session');

try {
    $items->clear();
    Mage::helper('catalog/product_compare')->calculate(); 
}
catch (Exception $e){
    //do nothing
}

You can add this code at the end of your compare list template (.phtml) but a clean option would be to either override the list block (Mage_Catalog_Block_Product_Compare_List) and add this code in the _afterToHtml() methods, or create an observer for the event core_block_abstract_to_html_after and check if the block passed to the observer matches your block (instanceof Mage_Catalog_Block_Product_Compare_List) then execute the code above.

I recommend overriding the block and adding the code in the _afterToHtml() method because the event is called for each rendered block and it may add an overhead to page rendering.

Related Topic