SHOW:
|
|
- or go back to the newest paste.
1 | <?php | |
2 | ||
3 | namespace OTC\MiniCart\Controller\Cart; | |
4 | ||
5 | use Magento\Framework\Controller\Result\JsonFactory; | |
6 | use Magento\Framework\Json\Helper\Data; | |
7 | use Magento\Framework\App\Action\Action; | |
8 | use Magento\Framework\App\Action\Context; | |
9 | use Magento\Checkout\Model\Session; | |
10 | use Psr\Log\LoggerInterface; | |
11 | ||
12 | class EmptyCart extends Action | |
13 | { | |
14 | /** | |
15 | * @var Session | |
16 | */ | |
17 | protected $checkoutSession; | |
18 | ||
19 | /** | |
20 | * @var JsonFactory | |
21 | */ | |
22 | protected $jsonFactory; | |
23 | ||
24 | /** | |
25 | * @var Data | |
26 | */ | |
27 | protected $jsonHelper; | |
28 | ||
29 | /** | |
30 | * @var LoggerInterface | |
31 | */ | |
32 | protected $logger; | |
33 | ||
34 | /** | |
35 | * @var Magento\Checkout\Model\Cart | |
36 | */ | |
37 | protected $cart; | |
38 | ||
39 | /** | |
40 | * EmptyCart constructor. | |
41 | * | |
42 | * @param Context $context | |
43 | * @param Session $session | |
44 | * @param JsonFactory $jsonFactory | |
45 | * @param Data $jsonHelper | |
46 | * @param LoggerInterface $logger | |
47 | */ | |
48 | public function __construct( | |
49 | Context $context, | |
50 | Session $session, | |
51 | JsonFactory $jsonFactory, | |
52 | Data $jsonHelper, | |
53 | LoggerInterface $logger, | |
54 | \Magento\Checkout\Model\Cart $cart | |
55 | ) { | |
56 | $this->checkoutSession = $session; | |
57 | $this->jsonFactory = $jsonFactory; | |
58 | $this->jsonHelper = $jsonHelper; | |
59 | $this->logger = $logger; | |
60 | $this->cart = $cart; | |
61 | parent::__construct($context); | |
62 | } | |
63 | ||
64 | /** | |
65 | * Ajax execute | |
66 | * | |
67 | */ | |
68 | public function execute() | |
69 | { | |
70 | $response = [ | |
71 | 'errors' => false | |
72 | ]; | |
73 | ||
74 | if ($this->getRequest()->isAjax()) { | |
75 | try { | |
76 | - | $allItems = $this->checkoutSession->getQuote()->getAllVisibleItems(); |
76 | + | $this->cart->truncate()->save(); |
77 | - | foreach ($allItems as $item) { |
77 | + | |
78 | - | $itemId = $item->getItemId();//item id of particular item |
78 | + | |
79 | - | $this->cart->removeItem($itemId); |
79 | + | |
80 | - | } |
80 | + | |
81 | - | $this->cart->save(); |
81 | + | |
82 | ]; | |
83 | $this->logger->critical($e); | |
84 | } | |
85 | } else { | |
86 | $response = [ | |
87 | 'errors' => true, | |
88 | 'message' => __('Need to access via Ajax.') | |
89 | ]; | |
90 | } | |
91 | /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ | |
92 | $resultJson = $this->jsonFactory->create(); | |
93 | return $resultJson->setData($response); | |
94 | } | |
95 | } |