Magento – Item not deleting from quote in Magento2

event-observermagento2quotequoteitem

I have used observer to delete the quote item.

Used this event controller_action_predispatch_checkout_index_index

This is the code of my etc/events.xml.

<event name="controller_action_predispatch_checkout_index_index">
    <observer name="change_quote_item_price" instance="Vendor\Module\Observer\DeleteItem" />
</event>

Then Vendor\Module\Observer\DeleteItem.php

<?php
namespace Vendor\Module\Observer;
use \Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface; 
use Magento\Framework\App\Response\Http as ResponseHttp;

class DeleteItem implements ObserverInterface{
  private $logger;
  protected $_messageManager;
  protected $_resource;
  protected $checkoutSession;
  protected $redirect;
  protected $cart;
  public function __construct(
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Framework\ObjectManagerInterface $objectManager,
    \Magento\Framework\App\ResourceConnection $resource,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Framework\App\Response\RedirectInterface $redirect,
    \Magento\Checkout\Model\Cart $cart
  ){
    this->_messageManager = $messageManager;
    $this->logger = $logger;
    $this->_resource = $resource;
    $this->checkoutSession = $checkoutSession;  
    $this->redirect = $redirect;
   $this->cart = $cart; 
 }
  public function execute(\Magento\Framework\Event\Observer $observer){

    try{
      $quote = $this->checkoutSession->getQuote();
            $quoteItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
            $isExist= false;
            foreach($quoteItems as $item) {
                    $productSku = $item->getSku();
                    $itemId = $item->getItemId();

                    $checkTable  = $this->checkProduct($productSku);
                    if($checkTable ){
                        $isExist= true;
                        $this->cart->removeItem($itemId)->save();                           
                        continue;
                    } 
                    $item->setQty(1);
                    $item->save();
            }
            $quote->collectTotals();

            $message = "You can't buy this product!!";
            if($isExist){
                $this->_messageManager->addError(__($message));             
                $controller = $observer->getControllerAction();
                $this->redirect->redirect($controller->getResponse(), 'checkout');
            }

    }catch (\Exception $e) {
        $this->logger->info(' --CheckoutBeforeException--  '.$e->getMessage());
    }
  }

 public function checkProduct($productSku){
   $connection = $this->getConnection();
   $sql = "select * from custom_table where sku='".$productSku."'";
   $resultProduct = $connection->query($sql);
   $resultQuery = $resultProduct->fetchAll();

   if(!empty($resultQuery)){ 
     $parent_sku = $resultQuery[0]['parent_sku'];
     return true;
   }
  }else{
    return false;
   }
  }

 public function getConnection(){
    $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
    return $connection;

  }

 }

This is not deleting the item, actually my observer file is firing. Item not deleting completely.

If navigated to cart page it is showing as summary with subtotal 0. Then in minicart also with qty 1.

Is any other code i need to use to delete the product from quote from itemId? Please anybody look into it and update me your answers. Thanks!!

Best Answer

Inject Magento\Quote\Api\CartRepositoryInterface class in constructor

public function __construct(\Magento\Quote\Api\CartRepositoryInterface $quoteRepository) 
{
    $this->quoteRepository = $quoteRepository;
}

now use bellow code to delete item from quote

$quote = $this->quoteRepository->getActive(QUOTE_ID);

foreach ($quote->getAllVisibleItems() as $item)
{
    $quote->deleteItem($item)->save();
}

$this->quoteRepository->save($quote);
Related Topic