4

I need to remove all the items from cart, below method remove the items in chenckout/cart/index page but header minicart section still dispaly the items even after refresh page too.

I have try this logic in custom controller app/code/Gworks/Cart/Controller/Items/Remove.php

public function deleteQuoteItems(){
    $checkoutSession = $this->getCheckoutSession();
    $allItems = $checkoutSession->getQuote()->getAllVisibleItems();//returns all teh items in session
    foreach ($allItems as $item) {
        $itemId = $item->getItemId();//item id of particular item
        $quoteItem=$this->getItemModel()->load($itemId);//load particular item which you want to delete by his item id
        $quoteItem->delete();//deletes the item
    }
}
public function getCheckoutSession(){
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager 
    $checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');//checkout session
    return $checkoutSession;
}

public function getItemModel(){
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager
    $itemModel = $objectManager->create('Magento\Quote\Model\Quote\Item');//Quote item model to load quote item
    return $itemModel;
}

after some search, I am trying to refresh minicart section using <custom-module>/etc/sections.xml but still the problem exist.

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="checkout/cart/index">
        <section name="cart"/>
    </action>
</config>

it confuse me, what I need to mention in action name. Actually I delete all item from checkout/cart/index page and their delete logic in separate ajax call in my custom controller gworks/items/remove. I tried both but nothing happen.

can anyone give a neat way to entirely remove all items from cart?

note: I know object manager is not recommended, If it is worked after that I can change to dependency injection method.

9

Your custom controller should be:

namespace Gworks\Cart\Controller\Items;

use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Cart as CustomerCart;

class Remove extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

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

    /**
     * @param Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param CustomerCart $cart
     */
    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        CustomerCart $cart
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->cart = $cart;

        parent::__construct($context);
    }

    public function execute()
    {
        $allItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
        foreach ($allItems as $item) {
            $itemId = $item->getItemId();
            $this->cart->removeItem($itemId)->save();
        }

        $message = __(
            'You deleted all item from shopping cart.'
        );
        $this->messageManager->addSuccessMessage($message);

        $response = [
            'success' => true,
        ];

        $this->getResponse()->representJson(
            $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($response)
        );
    }
}

Create sections.xml [Gworks/Cart/etc/frontend/sections.xml]

<?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="gworks/items/remove">
        <section name="cart"/>
    </action>
</config>

Now add following code js code:

$.ajax({
    url: '&lt;?php echo $block->getUrl('gworks/items/remove');?>',
    type: 'POST',
    showLoader: true,
    success: function (res) {
        if (res.messages) {
            $('[data-placeholder="messages"]').html(res.messages);
        }

        if (res.minicart) {
            $('[data-block="minicart"]').replaceWith(res.minicart);
            $('[data-block="minicart"]').trigger('contentUpdated');
        }
    }
});

Clear cache and delete var/generation/*

  • hi Sohel Where can i add this js code ? – Pratik Feb 3 '17 at 10:55
  • @Pratik inside your phtml – Sohel Rana Feb 3 '17 at 10:56
  • what is contentUpdated? @SohelRana – Rohan Hapani Jun 16 '17 at 4:35
  • 1
    @RohanHapani contentUpdated is magento custom event. – Sohel Rana Jun 16 '17 at 7:56
  • I removed cart product programmatically and product removed from cart but counter not proper working. can you give me any solution how to minicart refresh/reload? – Rohan Hapani Jun 16 '17 at 9:20
2

Something like this also can be worked out.

In your phtml file, button tag like this

<?php $_helper = $this->helper('Namespace\Modulename\Helper\Data'); ?>

<button id="clear-cart" class="action tocart primary" title="<?php echo __('Clear Cart') ?>" ><?php echo __('Clear Cart') ?></button>

and javascript function for onclick, like this

<script type="text/javascript">
        document.getElementById("clear-cart").onclick = function () {
            location.href = '<?php echo $_helper->getClearCartUrl(); ?>';
        };
    </script>

As I have called helper function on click location, we need to create helper function in any of our helper class. Like this,

public function getClearCartUrl(){
        $checkoutSession = $this->getCheckoutSession();
        $quoteId = $checkoutSession->getQuote()->getId();
        $quoteItem = $this->getQuoteModel()->load($quoteId);
        $quoteItem->delete();
        return $this->storeManager->getStore()->getBaseUrl() .'checkout/cart/' ;  //Need to load $this->storeManager in construct method to get Base URL
    }

    public function getCheckoutSession(){
        $checkoutSession = $this->_objectManager->get('Magento\Checkout\Model\Session');//checkout session
        return $checkoutSession;
    }

    public function getQuoteModel(){
        $quoteModel = $this->_objectManager->create('Magento\Quote\Model\Quote');//Quote item model to load quote
        return $quoteModel;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.