remove items from cart in controller - magento2
Your custom controller should be:
namespace Gworks\Cart\Controller\Items;
use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Cart as CustomerCart;
class Remove extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $checkoutSession;
/**
* @var \Magento\Checkout\Model\Cart
*/
protected $cart;
/**
* @param Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param CustomerCart $cart
*/
public function __construct(
Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
CustomerCart $cart
) {
$this->checkoutSession = $checkoutSession;
$this->cart = $cart;
parent::__construct($context);
}
public function execute()
{
$allItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
foreach ($allItems as $item) {
$itemId = $item->getItemId();
$this->cart->removeItem($itemId)->save();
}
$message = __(
'You deleted all item from shopping cart.'
);
$this->messageManager->addSuccessMessage($message);
$response = [
'success' => true,
];
$this->getResponse()->representJson(
$this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($response)
);
}
}
Create sections.xml [Gworks/Cart/etc/frontend/sections.xml]
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd"> <action name="gworks/items/remove"> <section name="cart"/> </action> </config>
Now add following code js code:
$.ajax({
url: '<?php echo $block->getUrl('gworks/items/remove');?>',
type: 'POST',
showLoader: true,
success: function (res) {
if (res.messages) {
$('[data-placeholder="messages"]').html(res.messages);
}
if (res.minicart) {
$('[data-block="minicart"]').replaceWith(res.minicart);
$('[data-block="minicart"]').trigger('contentUpdated');
}
}
});
Clear cache and delete var/generation/*