Magento2 : Mini cart removeItem is not working
-
16-04-2021 - |
Solution
Create Vendor/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Controller\Sidebar\RemoveItem" type="Vendor\Module\Controller\Sidebar\RemoveItem" />
</config>
Create Vendor/Module/Controller/Sidebar/RemoveItem.php
<?php
namespace Vendor\Module\Controller\Sidebar;
class RemoveItem extends \Magento\Checkout\Controller\Sidebar\RemoveItem
{
public function execute()
{
$itemId = (int)$this->getRequest()->getParam('item_id');
try {
$this->sidebar->checkQuoteItem($itemId);
$this->sidebar->removeQuoteItem($itemId);
return $this->jsonResponse();
} catch (\Magento\Framework\Exception\LocalizedException $e) {
return $this->jsonResponse($e->getMessage());
} catch (\Exception $e) {
$this->logger->critical($e);
return $this->jsonResponse($e->getMessage());
}
}
}
OTHER TIPS
Background:
In my case, I found out form_key was coming null in parms. Due to which below condition in execute() method
if (!$this->getFormKeyValidator()->validate($this->getRequest())) {
return $this->resultRedirectFactory->create()->setPath('*/cart/');
}
stops action of removing item from mini cart dropdown.
I also noticed form_key was part of cookies. The only problem was it was not getting sent as Form Data.
Solution:
I solved it by creating before plugin for execute() method of class
Magento\Checkout\Controller\Sidebar\RemoveItem
In plugin, I got form_key from cookies and setted it in param and BOOM
use Magento\Framework\App\RequestInterface;
class RemoveItem
{
protected $_request;
public function __construct(RequestInterface $request)
{
$this->_request = $request;
}
public function beforeExecute(
\Magento\Checkout\Controller\Sidebar\RemoveItem $subject
):array
{
if (!$this->_request->getParam('form_key')) {
$formKey = $this->_request->getCookie('form_key', null);
$this->_request->setParams(['form_key'=>$formKey]);
}
return [];
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange