Как удалить элемент предложения на основе условия в magento 2
У меня есть требование, как показано ниже.
Мне нужно прочитать все пункты котировок и их артикулы в пользовательской таблице,
Если значение совпадает, необходимо удалить этот элемент предложения и обновить кол-во 1 для оставшихся элементов, но этот код не работает для меня,
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;
}
}
Сейчас товар удаляется, но если перейти на страницу корзины, сводка отображается справа, где товар в корзине пуст
Может ли кто-нибудь разобраться в этом и сообщить мне решение,
Спасибо
2 answers
Попробуйте использовать следующий код:
use Magento\Framework\Controller\ResultFactory;
Class DeleteItem extends \Magento\Framework\App\Action\Action{{
protected $checkoutSession;
protected $cart;
protected $_resource;
protected $quoteItem;
protected $resultRedirect;
protected $messageManager;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Quote\Model\Quote\Item $quoteItem,
\Magento\Framework\Message\ManagerInterface $messageManager,
ResultFactory $resultRedirect
{
$this->cart = $cart;
$this->checkoutSession = $checkoutSession;
$this->_resource = $resource;
$this->quoteItem=$quoteItem;
$this->resultRedirect=$resultRedirect;
$this->messageManager = $messageManager;
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);
$itemid=$item->getItemId();
if($tableSKu){
$quoteItem=$this->quoteItem->load($itemid);
$quoteItem->delete();//deletes the item
continue;
}
$item->setQty(1);
$item->save();
}
$this->messageManager->addError( __('Item deleted Successfully !') );
$resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setPath("checkout");
return $resultRedirect;
}
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;
}
}
Я только что изменил ваш код, чтобы использовать модель quoteitem, потому что кажется, что ваш код удаляет элемент из коллекции, но не из сеанса проверки.
Если использование quoteitem не работает, то вам следует попытаться обновить данные корзины, как показано ниже:
Создать sections.xml файл в
Поставщик/пакет/и т.д./интерфейс
Напишите ниже код в этом
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="routeid/folder/DeleteItem"> <!-- Your action path -->
<section name="cart"/>
</action>
</config>