I have requirement like below.
I need to read all quote items and their sku, against the custom table,
If value matched, need to delete that quote item and update qty 1 for remaining items but this code is not working for me,
Class DeleteItem extends \Magento\Framework\App\Action\Action{{
protected $checkoutSession;
protected $cart;
protected $_resource;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart,
\Magento\Framework\App\ResourceConnection $resource,
{
$this->cart = $cart;
$this->checkoutSession = $checkoutSession;
$this->_resource = $resource;
parent::__construct($context);
}
public function execute() {
$quote = $this->checkoutSession->getQuote();
$quoteItems = $quote->getAllVisibleItems();
foreach($quoteItems as $item) {
$productSku = $item->getProduct()->getSku();
$tableSKu = $this->checkIfExist($productSku);
if($tableSKu){
$item->delete();
continue;
}
$item->setQty(1);
$item->save();
}
$message = "You alredy bought this Product";
$this->messageManager->addError(__($message));
$cartUrl = $this->_url->getUrl('checkout');
$this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse();
exit;
}
public function checkIfExist($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;
}
}
Right now the item is deleting but if navigated to cart page, the summary being shown right hand side, where item in cart is empty
Can anyone look into this and update me the solution,
Thanks