удалить товары из корзины в контроллере - magento2
Мне нужно удалить все товары из корзины, ниже приведен метод удаления товаров на странице chenckout/cart/index
, но раздел мини-карт заголовка по-прежнему отображает товары даже после обновления страницы.
Я попробовал эту логику в пользовательском контроллере app/code/Gworks/Cart/Controller/Items/Remove.php
public function deleteQuoteItems(){
$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
}
}
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;
}
После некоторого поиска я пытаюсь обновить раздел мини-карт с помощью <custom-module>/etc/sections.xml
, но проблема все еще существует.
<?xml version="1.0"?>
<!--
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="checkout/cart/index">
<section name="cart"/>
</action>
</config>
Это смущает меня, то, что мне нужно упомянуть в названии действия. На самом деле я удаляю все элементы из checkout/cart/index
страница и их логика удаления в отдельном вызове ajax в моем пользовательском контроллере gworks/items/remove
. Я пробовал и то, и другое, но ничего не вышло.
Может ли кто-нибудь дать аккуратный способ полностью удалить все товары из корзины?
Примечание: Я знаю, что диспетчер объектов не рекомендуется, если он будет работать после этого, я могу перейти на метод внедрения зависимостей.
2 answers
Ваш пользовательский контроллер должен быть:
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)
);
}
}
Создать 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>
Теперь добавьте следующий код js-кода:
$.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');
}
}
});
Очистите кэш и удалите var/generation/*
Что-то подобное также может быть разработано.
В вашем файле phtml тег кнопки выглядит следующим образом
<?php $_helper = $this->helper('Namespace\Modulename\Helper\Data'); ?>
<button id="clear-cart" class="action tocart primary" title="<?php echo __('Clear Cart') ?>" ><?php echo __('Clear Cart') ?></button>
И функция javascript для onclick, например
<script type="text/javascript">
document.getElementById("clear-cart").onclick = function () {
location.href = '<?php echo $_helper->getClearCartUrl(); ?>';
};
</script>
Поскольку я вызвал вспомогательную функцию по местоположению щелчка, нам нужно создать вспомогательную функцию в любом из наших вспомогательных классов. Вот так,
public function getClearCartUrl(){
$checkoutSession = $this->getCheckoutSession();
$quoteId = $checkoutSession->getQuote()->getId();
$quoteItem = $this->getQuoteModel()->load($quoteId);
$quoteItem->delete();
return $this->storeManager->getStore()->getBaseUrl() .'checkout/cart/' ; //Need to load $this->storeManager in construct method to get Base URL
}
public function getCheckoutSession(){
$checkoutSession = $this->_objectManager->get('Magento\Checkout\Model\Session');//checkout session
return $checkoutSession;
}
public function getQuoteModel(){
$quoteModel = $this->_objectManager->create('Magento\Quote\Model\Quote');//Quote item model to load quote
return $quoteModel;
}