How to delete cart Item by SKU or productId in magento 2
-
02-03-2021 - |
Question
I have retrieving all cart items and deleting the quote item by match with the product Sku,
Here is my code.
protected $checkoutSession;
protected $_itemModel;
protected $cart;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart,
\Magento\Quote\Model\Quote\Item $itemModel
{
$this->cart = $cart;
$this->checkoutSession = $checkoutSession;
$this->_itemModel = $itemModel;
parent::__construct($context);
}
public function execute() {
$quote = $this->checkoutSession->getQuote();
$quoteItems = $quote->getAllVisibleItems();
foreach($quoteItems as $item) {
$cartquote = $this->cart->getQuote();
$productSku = $item->getProduct()->getSku();
//$this->logger->info('ItemproductSku'.$productSku);
$checkExistedSKu = $this->getExistedSKu($productSku);
if($checkExistedSKu){
$itemId = $item->getItemId();
//$this->cart->removeItem($itemId)->save();
$this->_itemModel->load($item->getItemId())->delete();
}
$cartquote->updateItem($item->getId(), array( 'qty' => 1));
$cartquote->save();
}
public function getExistedSKu($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;
}
}
I am getting the product Sku by itemId and checking against my custom table, if Product Sku present in the table I am deleting that quote item and updating all other Items by Qty 1.
This code is not working for me, can anyone look into it where i am doing wrong here,
Any help will be Appreciated!!
Solution
Update for yourr comment
foreach($quoteItems as $item) {
$productSku = $item->getSku();
$checkExistedSKu = $this->getExistedSKu($productSku);
if($checkExistedSKu){
$item->delete();
continue;
}
$item->setQty(1);
$item->save();
}
$quote->collectTotals();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange