Please, how can I clear cart using javascript on Magento 2?
4 Answers
You may also like to do that by creating an 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>
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):
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);
}
{
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);
}
}
class Inchoo_EmptyCart_Model_Observer 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>
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');
}
}
Using Javascript,you cannot clear Cart directly . For archive thing ,you need do two things.
- Create a controller which deletes all items from Current cart
- Also using a javascript hit this controller
.
-
thanks for response, how can i clear cart using PHP on Controller? Commented Jun 10, 2016 at 11:30
-
Look at
vendor/magento/module-checkout/Controller/Cart/Delete.php
I think this is the controller you are looking for– LorenzoCommented Jun 10, 2016 at 11:53
You can use the same controller that Magento uses on the cart: checkout/cart/updatePost
So, if you are implementing this code on sidebar.js
you can import the 'mage/url'
as MageUrl
and use this code:
let url = MageUrl.build('checkout/cart/updatePost') +
'?form_key=' + $.mage.cookies.get('form_key') +
'&cart[]&update_cart_action=empty_cart';
self._ajax(url, {}, elem, null);
The elem
variable is a DOM element, you can also use $('.someClass')
...
Programatically we can clear Shopping Cart this way: Clearing cart session:
$collection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();
foreach( $collection as $item ){
Mage::getSingleton('checkout/cart')->removeItem( $item->getId() )->save();
}
Clearing Entire Checkout Session
Mage::getSingleton('checkout/session')->clear();
Let me know if it helps.
-
Although this is not the solution precisely according to your question ; I cordially seek your excuse for that. Commented Jun 10, 2016 at 11:40
-
-
Yeah, that's why I seek your excuse. I just gave you an idea how it works in m1. I am learning M2, hopefully can contribute to solve any M2 question in near future. Commented Jun 10, 2016 at 17:13