0

I Have 2 stores in my website, I want to clear the Mini-cart, Cart during store switch.

For this i wrote below code,

app\code\E25media\CustomBlocks\Controller\Cart\Index.php

<?php
namespace E25media\CustomBlocks\Controller\Cart;

use Magento\Checkout\Model\Cart;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Quote\Model\Quote;
class Index extends Action{
protected  $_modelCart;
protected $checkoutSession;
protected $_quote;

public function __construct(
    CheckoutSession $checkoutSession,
    Cart $modelCart, 
    Context $context, 
    Quote $quote )
{   
        //\Magento\Framework\App\Action\Context $context,
        $this->checkoutSession = $checkoutSession;
        $this->_modelCart = $modelCart;
        $this->_quote = $quote;
        parent::__construct($context);
}
public function execute()
{
    $cart = $this->_modelCart;
    $quoteItems = $this->checkoutSession->getQuote()->getItemsCollection();
    if( count($quoteItems) > 0){
        foreach($quoteItems as $item){
            $cart->removeItem($item->getId())->save(); 
            echo "Deleted".$item->getId();
        }
        echo 1;
    }else{
        echo 1;
    }
}
}

Above code successfully clear the cart but not the mini-cart. I added a click function when store switching.

<script type="text/javascript">
require(['jquery', 'Magento_Customer/js/customer-data', 'jquery/jquery.cookie'], function($,customerData){ 
$(".urlclick").click(function() {
    jQuery.ajax({
        url: '<?= $block->getUrl('store/cart/index', ['_use_rewrite' => false]); ?>',
        type: "GET",
        showLoader: true,
        cache: true,
        success: function (response) {
            if (response == 1) {
                var clickedUrl = $(this).attr("data");
                var sections = ['cart'];
                customerData.invalidate(sections);
                customerData.reload(sections, true);
                window.location.href = clickedUrl;
            }
        }
    });
});
});
</script>

Still the mini-cart is not clearing.Do i want to add any more to this? My store switch popup. enter image description here

Your Answer

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

Browse other questions tagged or ask your own question.