문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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();
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top