Magento2 Delete or Clear Cart Programmatically

Delete Magento2 Cart All items Programatically with out page refresh using jquery Require js.

 

<button type=”button” onclick=”clear_cart();”
name=”update_cart_action”
data-cart-empty=””
value=”empty_cart”
title=”<?= $block->escapeHtml(__(‘Clear Shopping Cart’)) ?>”
class=”action clear btn-cstm” id=”empty_cart_button”>
<span><?= /* @escapeNotVerified */ __(‘Clear Cart’) ?></span>
</button>

Create controller For Delete Cart Item:
app/code/Model/Orderrequest/Controller/Prescription


<?php
namespace Medley\Orderrequest\Controller\Prescription;

use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
use Magento\Framework\App\ObjectManager;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;

/**
* Login controller
*
* @method \Magento\Framework\App\RequestInterface getRequest()
* @method \Magento\Framework\App\Response\Http getResponse()
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Deletecart extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Session\Generic
*/
protected $session;

/**
* @var AccountManagementInterface
*/
protected $customerAccountManagement;

/**
* @var \Magento\Framework\Json\Helper\Data $helper
*/
protected $helper;

/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;

/**
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;

/**
* @var AccountRedirect
*/
protected $accountRedirect;

/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var Magento\Checkout\Model\Cart
*/
protected $cart;
/**
* Initialize Login controller
*
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\Json\Helper\Data $helper
* @param AccountManagementInterface $customerAccountManagement
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
*/
public function __construct(
Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Json\Helper\Data $helper,
AccountManagementInterface $customerAccountManagement,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Checkout\Model\Cart $cart
) {
parent::__construct($context);
$this->customerSession = $customerSession;
$this->helper = $helper;
$this->customerAccountManagement = $customerAccountManagement;
$this->resultJsonFactory = $resultJsonFactory;
$this->resultRawFactory = $resultRawFactory;
$this->cart = $cart;
}

/**
* Login registered users and initiate a session.
*
* Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
*
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{

/* $response = [
'errors' => false
];

if ($this->getRequest()->isAjax()) {
try {
$this->cart->truncate()->save();
$response['message'] = __('Empty Cart.');

} catch (\Exception $e) {
$response = [
'errors' => true,
'message' => __('Some thing went wrong.')
];
$this->logger->critical($e);
}
} else {
$response = [
'errors' => true,
'message' => __('Need to access via Ajax.')
];
}*/
/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
// $resultJson = $this->jsonFactory->create();
//return $resultJson->setData($response);

$response = [
'error' => false,
'message' => __('Deleated Success'),
'status_code' => 200
];
try {
$checkoutSession = $this->getCheckoutSession();
$allItems = $checkoutSession->getQuote()->getAllVisibleItems();//returns all teh items in session

foreach ($allItems as $item) {
$itemId = $item->getItemId();//item id of particular item
$quoteItem=$this->getItemModel()->load($itemId);//load particular item which you want to delete by his item id
$quoteItem->delete();//deletes the item
}

$this->cart->truncate()->save();

} catch (EmailNotConfirmedException $e) {
$response = [
'error' => true,
'message' => $e->getMessage(),
'status_code' => 400
];
} catch (InvalidEmailOrPasswordException $e) {
$response = [
'error' => true,
'message' => $e->getMessage(),
'status_code' => 400
];
} catch (LocalizedException $e) {
$response = [
'error' => true,
'message' => $e->getMessage(),
'status_code' => 400
];
} catch (\Exception $e) {
$response = [
'error' => true,
'message' => $e->getMessage(),
'status_code' => 400
];
}

$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}

public function getCheckoutSession(){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager
$checkoutSession = $objectManager->get('Magento\Checkout\Model\Session');//checkout session
return $checkoutSession;
}

public function getItemModel(){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();//instance of object manager
$itemModel = $objectManager->create('Magento\Quote\Model\Quote\Item');//Quote item model to load quote item
return $itemModel;
}
}

function clear_cart()
{
	 require(["jquery",'jquery/ui','mage/mage','common','sweetalert'], function ($){
	
		 $.ajax({
                url: "getUrl('orderrequest/prescription/deletecart') ?>",
                type: "GET",
				showLoader: true,
                success: function (data) {
					console.log(data);
					$(".counter").html("0");
					
					setTimeout(function(){ location.reload();  }, 500);

                   
                }
            }); 
   });
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By : XYZScripts.com