Magento2 – How to Remove Items from Cart in Controller

cartmagento2magento2.0.8mini-cart

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.

Best Answer

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/*