Magento 2.1.x – How to Remove Item from Cart

magento-2.1

In Magento 2.1.8, for minicart, inside Magento_Checkout/web/template/minicart/item/default.html around line 96, there's a chunk of code which shows the 'Remove' button.

            <div class="secondary">
                <a href="#" data-bind="attr: {'data-cart-item': item_id, title: $t('Remove item')}"
                   class="action delete">
                    <span data-bind="i18n: 'Remove'"></span>
                </a>
            </div>

But, it's not clear how this button sends data to the controller to delete selected item.

Could someone explain this knockout please?

Cheers

Best Answer

Magento remove the Item from the cart by using sidebar.js which you can find from,

vendor\magento\module-checkout\view\frontend\web\js\sidebar.js

In this js file below code is responsible to remove the Item from cart,

  events['click ' + this.options.button.remove] =  function (event) {
                event.stopPropagation();
                confirm({
                    content: self.options.confirmMessage,
                    actions: {
                        /** @inheritdoc */
                        confirm: function () {
                            self._removeItem($(event.currentTarget));
                        },

                        /** @inheritdoc */
                        always: function (e) {
                            e.stopImmediatePropagation();
                        }
                    }
                });
            };

After confirm message, It will call the

   _removeItem: function (elem) {
            var itemId = elem.data('cart-item');

            this._ajax(this.options.url.remove, {
                'item_id': itemId
            }, elem, this._removeItemAfter);
        },

It find the Item id as argument and send AJAX request to remove the Item from the cart. To remove the Item below controller is responsible,

vendor\magento\module-checkout\Controller\Sidebar\RemoveItem.php