4

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>
  • Did you try using create a sections.xml? – Sohel Rana Mar 15 '17 at 15:06
  • Yes I added sections.xml in etc/frontend – Abhishek Mar 15 '17 at 15:07
  • Update your question with detail like link, sections.xml etc. – Sohel Rana Mar 15 '17 at 15:08
  • Here in Ajax , url:'/customer/data/store/store_id/'+store_id, Store.php is controller file. On change of store I have to clear cart. – Abhishek Mar 15 '17 at 15:19
  • What's your controller class. It's really important to what's return. – Sohel Rana Mar 15 '17 at 15:24
4

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>
  • i have follow your code, item is remove but quantity remove only 1 from minicart – Ajay Patel Nov 21 '17 at 4:52
  • @abhishek can you please explain your answer little more – Mujahidh Jun 24 at 6:13
1

enter image description here

Followed your code all works fine but the mini cart is not completly empty PFA.

Items get deleted but the price still shows. Do you have any clue?

0

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

@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
  • Completely unrelevant information. Looks like spambot message :) – Dmitri Portenko Dec 14 '17 at 11:03

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.