1

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!!

8
  • Did you created sections.xml file? Commented Jul 17, 2019 at 9:54
  • @RohanHapani, No I am using even and observer, how to create section file, can u pls update me, I have used above code
    – Manjunath
    Commented Jul 17, 2019 at 9:59
  • @RohanHapani, Can you pls update your answer what change i need to make..
    – Manjunath
    Commented Jul 17, 2019 at 10:10
  • When do you want the item to be deleted from quote?
    – aravind
    Commented Jul 17, 2019 at 13:29
  • @aravind, if checkProduct function return value is true..
    – Manjunath
    Commented Jul 17, 2019 at 13:34

2 Answers 2

1

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);
3
  • do i need to use this line?$quote = $this->quoteRepository->getActive(QUOTE_ID); because already i am loading quote items
    – Manjunath
    Commented Jul 18, 2019 at 6:59
  • okay then no need i just give you reference
    – Hiren
    Commented Jul 18, 2019 at 7:12
  • Still same issue, its not clearing the item completely.. i can see empty summary with total 0
    – Manjunath
    Commented Jul 18, 2019 at 7:17
0

Actually this deletes the product from cart,as well as from tables in quote_item, quote_item_option. I have just now tested using custom controller

\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart

create property

$this->checkoutSession   = $checkoutSession;
$this->cart              = $cart;

call quote function for removing item by item id

 $allItems =  $this->checkoutSession->getQuote()->getAllVisibleItems();
 foreach ($allItems as $item) {
       $cartItemId = $item->getItemId();
       $this->cart->removeItem($cartItemId)->save();
 }
11
  • hi @aravind, I am trying it now.
    – Manjunath
    Commented Jul 17, 2019 at 13:52
  • 1
    hi @aravind, same issue after that also..
    – Manjunath
    Commented Jul 17, 2019 at 14:01
  • Do i need to use save() method after that line?
    – Manjunath
    Commented Jul 17, 2019 at 14:24
  • did you find the solution?
    – aravind
    Commented Jul 18, 2019 at 5:04
  • hi @aravind, No the one u given is not worked for me
    – Manjunath
    Commented Jul 18, 2019 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.