Domanda

Using magento 2.2, I need to remove all items in current cart while going to other root category on my front page. I want some advice for coding this event.

È stato utile?

Soluzione

You can delete cart items using below code.

public function deleteQuoteItems()
{
  $checkoutSession = $this->getCheckoutSession();
  $allItems = $checkoutSession->getQuote()->getAllVisibleItems();

    foreach ($allItems as $item) {
     $itemId = $item->getItemId();//item id of particular item
     $quoteItem=$this->getItemModel()->load($itemId);
     $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;
}

MiniCart is rendering using Local Storage.

To clear it check here. Very Well Explained. How to add "Empty Cart" button to minicart

Altri suggerimenti

Try the below script to delete cartItems.

root/scripts/clearCartItem.php

    <?php


    use Magento\Framework\App\Bootstrap;
    require dirname(__FILE__) . '/../app/bootstrap.php';

    $bootstrap = Bootstrap::create(BP, $_SERVER);

    $obj = $bootstrap->getObjectManager();
    $state = $obj->get('Magento\Framework\App\State');
    $state->setAreaCode('frontend');
    try {
        $checkoutSession = $obj->get('\Magento\Checkout\Model\Session');
        $cart = $obj->get('\Magento\Checkout\Model\Cart');


        $allItems = $checkoutSession->getQuote()->getAllVisibleItems();
        foreach ($allItems as $item) {
            $itemId = $item->getItemId();
            $cart->removeItem($itemId)->save();
        }

        echo "Cleared all items in cart";
    } catch (\Exception $e) {
        echo $e->getMessage();
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top