Magento 2 – How to Clear Mini Cart Programmatically

cart-itemsmagento2mini-cartprogrammatically

enter image description hereI am using this solution and get referenece from Here. But It dose not update mincart after page refresh. Although it deletes items from quote_item table. I am also trying deleting quote id from database.But didn't work.

 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 page refresh It is showing items in minicart. I tried to unset checkout session but didin't work. Please help.

[EDIT]

I have added this code in my phtml file

<script type="text/javascript">
    require([
    "jquery"
    ], function($){
        $('#customerStore').change(function(){
            var store_id = $(this).val(); 
            $.ajax({
            url:'/customer/data/store/store_id/'+store_id,
            type:'get',
            dataType: 'json',
            beforeSend:function(){
                $('#loader').show();
            },
            success:function(res){
                if (res.messages) {
                    alert(res);
                $('[data-placeholder="messages"]').html(res.messages);
                }
                if (res.minicart) {
                    alert('if'+res.minicart);
                    $('[data-block="minicart"]').replaceWith(res.minicart);
                    $('[data-block="minicart"]').trigger('contentUpdated');
                }
            },
            complete:function(){
                $('#loader').hide();
                location.reload();
            }
            });
        });
    });

on ajax action I call script to clear cart

Store.php controller

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Vendor\Module\Controller\Data;

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

class Store extends \Magento\Framework\App\Action\Action
{
    /**
     * Show customer tickets
     *
     * @return \Magento\Framework\View\Result\Page
     * @throws NotFoundException
     */
    protected $_customerSession;
    protected $_response;
    protected $cart;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Response\Http $response,
         CustomerCart $cart
    ) {
        $this->cart = $cart;
        $this->_customerSession = $customerSession;
        $this->_response = $response;
        parent::__construct($context);
    }

    public function execute()
    {   
         $store_id = $this->getRequest()->getParam('store_id');
         //$customer   =   $this->_customerSession->create();
         //$customer_store =   $this->_customerSession->getCustomer()->getData('stores');
         //echo "<pre>"; print_r($this->_customerSession->getData()); 
         $this->deleteQuoteItems();

         $this->_customerSession->setCurrentStore($store_id);
    }


    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
        $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)
        );
    }

    public function getCheckoutSession(){
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager 
        $checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');//checkout session
        return $checkoutSession;
        //echo "<pre>"; print_r($checkoutSession->getData()); die();
    }

    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;
    }


}

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="vendor/module/data/store">
        <section name="cart"/>
    </action>
</config>

Best Answer

Somehow I found solution.

In phtml file I have added customer-data js method

require([
    'jquery',
    'Magento_Customer/js/customer-data'
    ], function($,customerData){
        $('#customerStore').change(function(){
            var store_id = $(this).val();
            var sections = ['cart'];
            $.ajax({
            url:'/customer/data/store/store_id/'+store_id,
            type:'get',
            dataType: 'html',
            beforeSend:function(){
                $('#loader').show();
            },
            success:function(response){
                customerData.invalidate(sections);
                $('#loader').hide();
                location.reload();
            }
            });
        });
    });

In my controller file Store.php I have deleted quote item from table

public function deleteQuoteItems(){
$checkoutSession = $this->getCheckoutSession();
//$quote = $this->$checkoutSession->getQuote();

 $quote_Id= $this->cart->getQuote()->getId();

//print_r($checkoutSession->getQuote()->getData());

$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();
}
if(!empty($quote_Id)){
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 // $quoteModel = $objectManager->create('Magento\Quote\Model\Quote');
 // $quoteModel->delete($quote_Id); 
 $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
 $connection = $resource->getConnection();
 $tableName = $resource->getTableName('quote');
    $sql = "DELETE  FROM " . $tableName." WHERE entity_id = ".$quote_Id;
    $connection->query($sql);
 }
}

Updated sections.xml. Remove vendor from action name

<?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="module/data/store">
        <section name="cart"/>
    </action>
</config>
Related Topic