Magento2 | PWA | GraphQL

Add "Empty Cart" button to Minicart magento2


In this post we wiil check how to add "Empty Cart" link button on minicart Magento2.

Let's start by creating custom module.

You can find complete module on Github at Magelearn_ClearCart



Create folder inside app/code/Magelearn/ClearCart

Add registration.php file in it:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magelearn_ClearCart',
    __DIR__
);

Add composer.json file in it:

{
    "name": "magelearn/module-clear-cart",
    "description": "Add empty cart button in minicart magento2.",
    "type": "magento2-module",
    "require": {},
    "authors": [
        {
            "name": "vijay rami",
            "email": "vijaymrami@gmail.com"
        }
    ],
    "license": "proprietary",
    "minimum-stability": "dev",
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\ClearCart\\": ""
        }
    }
}

Add etc/module.xml file in it:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magelearn_ClearCart" setup_version="1.0.0" >
        <sequence>
            <module name="Magento_Theme"/>
            <module name="Magento_Checkout"/>
            <module name="Magento_Tax"/>
        </sequence>
    </module>
</config>
Now, first we will check how to add this 'Empty Cart Now' button on Minicart at front end.
For that we will override vendor/magento/module-checkout/view/frontend/layout/default.xml file.

So, We will create view/frontend/layout/default.xml file. 
Here we will add our custom JS component file and template file under <item name="promotion" xsi:type="array"> node.

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
          <css src="Magelearn_ClearCart::css/clearcart.css" />          
    </head> 
    <body>
        <referenceBlock name="minicart">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="types" xsi:type="array"/>
                    <item name="components" xsi:type="array">
                        <item name="minicart_content" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="promotion" xsi:type="array">
                                    <item name="component" xsi:type="string">Magelearn_ClearCart/js/view/minicart</item>
                                    <item name="config" xsi:type="array">
                                        <item name="template" xsi:type="string">Magelearn_ClearCart/clearcart/content</item>
                                    </item>
                                </item>
                            </item>                            
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Now, as per the code highlighted in above file, we will create our JS component file and write logic to remove product from cart. We will also create template file and write logic to add "Empty Cart" button HTML.

But before creating those file we will check how to add this empty cart URL via window.checkout variable and define our controller logic.

Create etc/frontend/di.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Cart\Sidebar">
        <plugin name="empty_cart_url" type="Magelearn\ClearCart\Plugin\Cart\ConfigPlugin" sortOrder="20" />
    </type>
</config>

Now add Plugin/Cart/ConfigPlugin.php file.

<?php

namespace Magelearn\ClearCart\Plugin\Cart;

use Magento\Framework\UrlInterface;

class ConfigPlugin
{
    /**
     * @var UrlInterface
     */
    protected $url;

    /**
     * ConfigPlugin constructor.
     * @param UrlInterface $url
     */
    public function __construct(
        UrlInterface $url
    ) {
        $this->url = $url;
    }

    /**
     * @param \Magento\Checkout\Block\Cart\Sidebar $subject
     * @param array $result
     * @return array
     */
    public function afterGetConfig(
        \Magento\Checkout\Block\Cart\Sidebar $subject,
        array $result
    ) {
        $result['emptyMiniCart'] = $this->url->getUrl('clearcart/cart/emptycart');
        return $result;
    }
}

Now as per defined in above file, we have define our custom URL for empty cart.
For that first create etc/frontend/routes.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="clearcart" frontName="clearcart">
            <module name="Magelearn_ClearCart" />
        </route>
    </router>
</config>

Also Create Controller/Cart/EmptyCart.php file.

<?php

namespace Magelearn\ClearCart\Controller\Cart;

use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Json\Helper\Data;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Session;
use Psr\Log\LoggerInterface;

class EmptyCart extends Action
{
    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var JsonFactory
     */
    protected $jsonFactory;

    /**
     * @var Data
     */
    protected $jsonHelper;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var Magento\Checkout\Model\Cart
     */
    protected $cart;

    /**
     * EmptyCart constructor.
     *
     * @param Context $context
     * @param Session $session
     * @param JsonFactory $jsonFactory
     * @param Data $jsonHelper
     * @param LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        Session $session,
        JsonFactory $jsonFactory,
        Data $jsonHelper,
        LoggerInterface $logger,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->checkoutSession = $session;
        $this->jsonFactory = $jsonFactory;
        $this->jsonHelper = $jsonHelper;
        $this->logger = $logger;
        $this->cart = $cart;
        parent::__construct($context);
    }

    /**
     * Ajax execute
     *
     */
    public function execute()
    {
        $response = [
            'errors' => false
        ];

        if ($this->getRequest()->isAjax()) {
            try {
                $this->cart->truncate()->save();
                $response['message'] = __('Empty Cart.');
                
            } catch (\Exception $e) {
                $response = [
                    'errors' => true,
                    'message' => __('Some thing went wrong.')
                ];
                $this->logger->critical($e);
            }
        } else {
            $response = [
                'errors' => true,
                'message' => __('Need to access via Ajax.')
            ];
        }
        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultJson = $this->jsonFactory->create();
        return $resultJson->setData($response);
    }
}

We will also create sections.xml file, which will update the cart section when our custom action will be called.

Create etc/frontend/sections.xml file.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="clearcart/cart/emptycart">
        <section name="cart"/>
    </action>
</config>

Now we will add our JS component file at view/frontend/web/js/view/minicart.js

define([
    'jquery',
    'Magento_Checkout/js/view/minicart',
    'Magento_Ui/js/modal/alert',
    'Magento_Ui/js/modal/confirm'
], function ($ ,Component, alert, confirm) {
    'use strict';

    return Component.extend({
        confirmMessage: $.mage.__('Are you sure you would like to remove all items from the shopping cart?'),
        emptyCartUrl: window.checkout.emptyMiniCart,

        emptyCartAction: function (element) {
            var self = this,
                href = self.emptyCartUrl;
            $(element).on('click', function () {
                var el = this;
                confirm({
                    content: self.confirmMessage,
                    actions: {
                        confirm: function () {
                            self._removeAllItems(href, el);
                        },
                        always: function (event) {
                            event.stopImmediatePropagation();
                        }
                    }
                });
            });
        },

        _removeAllItems: function (href, elem) {
            $.ajax({
                url: href,
                type: 'post',
                dataType: 'json',
                beforeSend: function () {
                    $(elem).attr('disabled', 'disabled');
                },
                complete: function () {
                    $(elem).attr('disabled', null);
                }

            }).done(function (response) {                
                if (!response.errors) {
                    var msg = response.message;                    
//                    if (msg) {
//                        alert({
//                            content: msg
//                        });
//                    }
                    window.location.reload();
                } else {
                    var msg = response.message;                    
                    if (msg) {
                        alert({
                            content: msg
                        });
                    }                    
                }
            }).fail(function (error) {
                console.log(JSON.stringify(error));
            });
        }
    });
});

We will also add view/frontend/web/template/clearcart/content.html file.

<!-- ko if: getCartParam('summary_count') -->
    <div class="actions">
        <div class="secondary empty-cart-button">
            <a class="action empty-cart" id="empty-minicart"
            	data-bind="afterRender: emptyCartAction">
                <span><!-- ko i18n: 'Empty Cart Now' --><!-- /ko --></span>
            </a>
        </div>
    </div>
 <!-- /ko -->

You can read more about afterRender from here and there.

We will also add our CSS file at view/frontend/web/css/clearcart.css

0 Comments On "Add "Empty Cart" button to Minicart magento2"

Back To Top