Magento 2 : How to clear mini cart programatically
-
13-04-2021 - |
Question
I 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>
La solution
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>
Autres conseils
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;
}
Just do following
try{
$cart = $this->_objectManager->create("Magento\Checkout\Model\Cart");
$cart->truncate();
$cart->getQuote()->setTotalsCollectedFlag(false);
$cart->save();
}
catch(\Exception $e){
//throw $e;
}
@Nikhil I think you have to clear your cache, view_processed, page_cache, generation from var folder. Also remove frontend, requirejs folder from pub/static folder. And then run
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy