There’s no “EMPTY CART” on Magento’s cart page

There’s no “EMPTY CART” on Magento’s cart page

Or at least, hasn’t been there yet. Recently I had to do one too many cart tests, and one of most annoying things was when I had to empty it, As anyone – I had to click it one by one. Today I’m going to explain how can you avoid this by simply creating one simple extension, and enabling “Empty cart” link functionality.

It really isn’t that hard. All you have to do is create yourselves a small extension that consists of Block, Controller, XML, Model and Template with very little logic inside.

So let’s start with XML (config.xml):

<config>
    <modules>
        <Inchoo_EmptyCart>
            <version>0.1.0</version>
        </Inchoo_EmptyCart>
    </modules>
    <global>
        <models>
            <emptycart>
                <class>Inchoo_EmptyCart_Model</class>
            </emptycart>
        </models>
        <blocks>
            <emptycart>
                <class>Inchoo_EmptyCart_Block</class>
            </emptycart>
        </blocks>
    </global>
    <frontend>
        <routers>
            <emptycart>
                <use>standard</use>
                <args>
                    <module>Inchoo_EmptyCart</module>
                    <frontName>emptyCart</frontName>
                </args>
            </emptycart>
        </routers>
        <events>
            <core_block_abstract_to_html_after>
                <observers>
                    <inchoo_emptycart_init>
                        <type>singleton</type>
                        <class>Inchoo_EmptyCart_Model_Observer</class>
                        <method>injectLinkEmptyCart</method>
                    </inchoo_emptycart_init>
                </observers>
            </core_block_abstract_to_html_after>
        </events>
    </frontend>
</config>

Besides there’s a hoot to event here (for link injection into cart), it’s pretty much basic stuff.

Now on to bit more fun stuff. Model (Observer.php):

<?php
class Inchoo_EmptyCart_Model_Observer
{
	const MODULE_NAME = 'Inchoo_EmptyCart';
 
	public function injectLinkEmptyCart($observer = NULL)
	{
		if (!$observer) {
			return;
		}
 
		if ('checkout.cart.methods.onepage.top' == $observer->getEvent()->getBlock()->getNameInLayout()) {
 
			if (!Mage::getStoreConfig('advanced/modules_disable_output/'.self::MODULE_NAME)) {
				$transport = $observer->getEvent()->getTransport();
				$block = new Inchoo_EmptyCart_Block_Injection();
				$block->setPassingTransport($transport['html']);
				$block->toHtml();
			}
		}
 
		return $this;
	}
}

And Block (Injection.php):

<?php
class Inchoo_EmptyCart_Block_Injection extends Mage_Core_Block_Text
{
	public function setPassingTransport($transport)
	{
		$this->setData('text', $transport.$this->_generateContent());
	}
 
	private function _generateContent()
	{
		$_extensionDirectory = dirname(dirname(__FILE__));
		$_javascriptFileName = 'content.phtml';
		$_templateDirectory = 'template';
		$_fileContents = file_get_contents($_extensionDirectory . DS . $_templateDirectory . DS . $_javascriptFileName);
		return eval('?>' . $_fileContents);
	}
}

Now what happened here you might ask. Since this is a helper extension, I wanted to keep template file inside extension directory, as it’s simple it can get. And both Model and Block provided me with that. Only thing missing in this part is content.phtml, which consists of these few lines:

<span id="inchoo-empty-cart">
	<a href="<?php echo Mage::getUrl('emptyCart/')?>">
		<?php echo Mage::helper('core')->__("Empty Cart");?>
	</a>
</span>

At this moment you have injected link “Empty cart” into Magento’s Cart page. Finally the extensions logic is here (IndexController.php):

<?php
class Inchoo_EmptyCart_IndexController extends Mage_Core_Controller_Front_Action
{
	public function indexAction()
	{
		//Get cart helper
		$cartHelper = Mage::helper('checkout/cart');
 
		//Get all items from cart
		$items = $cartHelper->getCart()->getItems();
 
		//Loop through all of cart items
		foreach ($items as $item) {
			$itemId = $item->getItemId();
			//Remove items, one by one
			$cartHelper->getCart()->removeItem($itemId)->save();
		}
 
		//Redirect back to cart or wherever you wish
		$this->_redirect('checkout/cart');
	}
}

And that’s pretty much it. In action it looks like this:

And for those of you who are too lazy to create extension :D, you can download it here. But note that you’re using it without any warranties and please create a backup before you install it.

I hope this helped someone with same frustration I had!

Cheers!

You made it all the way down here so you must have enjoyed this post! You may also like:

How to connect Google Analytics 4 to Magento 2 Bojan Mareljic
Bojan Mareljic, | 35

How to connect Google Analytics 4 to Magento 2

3 best open-source eCommerce platforms in 2021 Zrinka Antolovic
Zrinka Antolovic, | 7

3 best open-source eCommerce platforms in 2021

eCommerce Returns Management – a simple solution from the Fashion industry Zrinka Antolovic
Zrinka Antolovic, | 12

eCommerce Returns Management – a simple solution from the Fashion industry

33 comments

  1. hello ,gys
    I have created module I want to am Create a Phtml page callto cart.phtml
    iam using xml

    but my block method return not result
    please help mee
    please

  2. Hi, i was thinking about put a similar button on the customer edit page, on magento admin, did you found a similar solution?
    I was looking for these functions in this file: /app/design/adminhtml/default/default/template/customer/tab/cart.phtml, but those functions can empty only item by item by default.
    If you have any suggestions, please send me.

  3. Hello how can I make a redirect to the same page? User can press a EmptyCart button from any page through the right column. Really need that would redirect occurred on the page where the user was in the moment the button is pressed.

  4. You can set all the item to 0 and update the cart. Like said in one of the first comment, we don’t want the customer to remove items…

  5. Hi,

    Thank you for your extension. I put it in on my website, but i have a problem of route. When i click on the link, i redirectly in my 404 page. I don’t undestand but my plugin is enabled. Have you an idea ?

    Thanks

    Djoo

  6. @Matt:
    Make sure your config file is setup correctly, and your Observer file is named correctly. You should be sure to use the proper naming scheme in all files in this and other custom modules. It looks like yours may not be named quite correctly.

    If you are still using the “Inchoo” namespace, make sure the class name of your observer file reads:

    class Inchoo_EmptyCart_Model_Observer

    For some reason, it looks like yours is just showing up as:

    class Empty_Cart_Model_Observer
  7. Hello,

    I am running 1.6.1 and am getting this error also.

    Please let me know how to fix this.

    Mage_Core_Exception’ with message ‘Mage registry key “_singleton/Empty_Cart_Model_Observer” already exists’ in /var/www/vhosts/xxxxxxx.com/httpdocs/app/Mage.php:550

  8. Hi Guys,

    Sorry for the Noob question here, but can someone point me in the right direction and give me the actual path to the cart.phtml?

    Am I right in thinking is is this?

    app\design\frontend\default\\template\checkout?

    Also, whereabouts do I insert this code (see below) as a link within this file?

    <button type="button" title="<?php echo $this->__( 'Empty Cart' ) ?>" class="button btn-empty" onclick="setLocation( '<?php echo $this->getUrl('emptyCart/index/index') ?>' )"><span><span><?php echo $this->__( 'Empty Shopping Cart' ) ?></span></span></button> 

    Cheers

  9. This module looks great, but I think you could get a little more efficiency out of it by not calling save() until after the loop. That way you only have to make one DB call instead of one for each item you’re removing.

  10. I have found this bug in exception log after copying the EmptyCart Module inside my Inchoo folder and my whole website went down….

    Mage_Core_Exception’ with message ‘Mage registry key “_singleton/Empty_Cart_Model_Observer” already exists’ in /var/www/vhosts/xxxxxxx.com/httpdocs/app/Mage.php:550

  11. I don’t know if the “qty” class is applied to the qty field in all templates, but for mine I run a Javascript command:

    $$('.qty').each(function (el) {
      el.value = 0;
    });

    This sets all of the Quantities to 0 and I update the cart and voila! everything is gone. I could add some code to submit the form but I usually want to keep 1 product around so I set all to 0, set one to 1, and then submit.

  12. magento\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php

    $cookieParams = array(
    ‘lifetime’ => $cookie->getLifetime(),
    ‘path’ => $cookie->getPath(),
    ‘domain’ => $cookie->getConfigDomain(),
    ‘secure’ => $cookie->isSecure(),
    ‘httponly’ => $cookie->getHttponly()
    );

    change to

    $cookieParams = array(
    ‘lifetime’ => $cookie->getLifetime(),
    ‘path’ => $cookie->getPath()
    );

    i use this , and solve my problem. i hope someone can get helping form this.

  13. Thanks for reply Matt… I’m afraid I don’t have the slightest idea what to look for. I found a mod that worked on my 1.3 site in the past but I can’t find it now..

  14. They made a bunch of changes with how things are set up and how they run going from 1.3 to 1.4…you may want to check out some of the differences between the different versions of Magento to see what all changed and then update accordingly.

  15. I just used Matt W’s code above to add the button to my checkout and it works like a charm. You guys are awesome. Does anyone else think it’s weird there isn’t an empty cart in there by default? Sometimes you just have a ton of stuff that you wanted to calculate shipping on and then start over.

    Cheers to you both!

  16. I figured it out!

    For some reason, the link didn’t inject itself into the cart page, so I ended up just creating the button by hand on cart.phtml like this:

    <button type="button" title="<?php echo $this->__( 'Empty Cart' ) ?>" class="button btn-empty" onclick="setLocation( '<?php echo $this->getUrl('emptyCart/index/index') ?>' )"><span><span><?php echo $this->__( 'Empty Shopping Cart' ) ?></span></span></button>

    Thanks again for all of the great work!

  17. Having some trouble getting the link to actually show up on the cart page. Running Magento 1.5.1.0. Has it been tested on there and I am just messing something up, or does it only work on older versions?

    I am in need of a clear cart button, but I just can’t seem to get this working correctly…

    Thanks for the help, and for all of the great posts here. Keep up the good (and extremely helpful) work.

  18. Nice bit of code. I also find it a nusance when testing and you find you’ve got 500 items in your cart.

    My solution until now is usually to clear the server cache lol.

  19. Ah, nice one. I always made a small JS function that just fills zero’s for the all the product qty’s and than submits the update cart link. Your extension is way more easy, thx!

  20. @Bruno – At first, I wrote “Recently I had to do one too many cart tests”… That’s why I wrote this extension, it might help someone.

    Otherwise, both you and Toni are right, it depends on store owner, or at least it should. 😀

    Cheers!

  21. We don’t want the user empty the items in the Cart, but that they checkout the items in that cart ;o)

    That’s why Mage does not have an Empty Cart link by default, eheheh

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.