Update all quote items with qty 1 in magento2
-
03-03-2021 - |
Frage
I am trying to update all the quote item qty as soon as we navigated to the cart page.
by using below code.
$quote = $this->checkoutSession->getQuote();
$quoteItems = $quote->getAllVisibleItems();
foreach($quoteItems as $item) {
$productSku = $item->getSku();
$item->setQty(1);
$item->save();
}
The above code working fine if we run from the script for or from any of the controller file.
I am looking for code to implement in event and observers,
Is there any event for this, once navigated to cart page i need update qty for each item as 1.
Can anyone suggest which event is worth for it.
Thanks
Lösung
You can use the Controller dispatch event of
Cart page controller_action_predispatch_checkout_cart_index
.
On this event fire an observer and update the Cart Qty.
Observer
<?php
namespace StackExchange\Magento\Observer\CheckoutCart;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\Exception\LocalizedException;
class UpdateQty implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
protected $quoteRepository;
/**
* @var CheckoutSession
*/
private $checkoutSession;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger,
CheckoutSession $checkoutSession,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
$this->checkoutSession = $checkoutSession;
$this->logger = $logger;
}
/**
* Execute observer
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(
\Magento\Framework\Event\Observer $observer
) {
$this->logger->debug(__METHOD__);
$quote = $this->checkoutSession->getQuote();
$quoteItems = $quote->getAllVisibleItems();
if(!count($quoteItems) <= 0){
return $this;
}
try {
foreach($quoteItems as $item) {
$productSku = $item->getSku();
$item->setQty(1);
$item->save();
}
$this->quoteRepository->save($quote);
} catch (LocalizedException $e) {
$this->logger->critical($e->getMessage());
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange