Magento2 | PWA | GraphQL

Magento2 Events After add/remove products from cart and add new products into cart based on the cart items


With Magento2 events/observer you can do lots of additional functionalities by tweaking default one.
Here in this article we will check how Magento2 events works when we add/remove items from cart.

In this example, we will check the product SKU and if it is discounted product SKU and having qty greater than one then we will add another half price discounted products into cart.

And when this main discounted product is removed from cart then we also removed half price discounted product from the cart. 

Before do this we have duplicated same SKU product with half price and also modify checkout/cart listing page templete and hide qty +/- button for this duplicated product.

Suppose that SKU of discouted product = 1244VR

SKU of product with duplicated half price = 1244VR-1

ID of product with duplicated half price = 13482

We will use checkout_cart_product_add_after event to observe product after add into cart and sales_quote_remove_item event when products remove from cart.

Add your events in etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="customprice" instance="Magelearn\CustomProductPrice\Observer\CustomPrice" />
    </event>
    <event name="sales_quote_remove_item">
        <observer name="removefaucet" instance="Magelearn\CustomProductPrice\Observer\RemoveProduct" />
</event> </config>
Now Add your observer Magelearn/CustomProductPrice/Observer/CustomPrice.php  to check products after added inot cart.
<?php
    
    namespace Magelearn\CustomProductPrice\Observer;
use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\RequestInterface; class CustomPrice implements ObserverInterface { protected $logger; protected $_checkoutSession; protected $_cart; protected $_productRepository; public function __construct( \Psr\Log\LoggerInterface $logger, \Magento\Checkout\Model\SessionFactory $checkoutSession, \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart ) { $this->logger = $logger; $this->_checkoutSession = $checkoutSession; $this->_productRepository = $productRepository; $this->_cart = $cart; } public function execute(\Magento\Framework\Event\Observer $observer) { $quoteItem = $observer->getEvent()->getQuoteItem(); $item = $observer->getEvent()->getData('quote_item'); $product = $observer->getEvent()->getData('product'); $min_qty = 1; $item = ( $item->getParentItem() ? $item->getParentItem() : $item ); $sku = $item->getSku(); $qty = $item->getQty(); $item_price = $item->getPrice(); if($sku == '1244VR' && ($qty > 1)) { $cartitem = $this->_cart->getQuote()->getItemByProduct($product); if ($item) { $add_qty = $qty - 1; $this->_cart->updateItem($cartitem->getId(), $add_qty); } if($product->getId() != 13482){ $params = array( 'product' => 13482, 'qty' => '1' ); $_product = $this->_productRepository->getById(13482); $this->_cart->addProduct($_product,$params); $this->_cart->save(); } } } }
Now Add your observer Magelearn/CustomProductPrice/Observer/RemoveProduct.php  when we remove products from cart and check if we remove discounted products then system also remove the half price duplicate product.
<?php

namespace Magelearn\CustomProductPrice\Observer;
use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\RequestInterface; use Magento\Checkout\Model\Session; use Magento\Framework\Serialize\Serializer\Json as JsonSerializer; use Magento\Checkout\Model\Cart as CustomerCart; class RemoveProduct implements ObserverInterface
{ /** * @var RequestInterface */ protected $_request; /** * Json Serializer * * @var JsonSerializer */ protected $jsonSerializer; protected $cart; /** * Set payment fee to order * * @param EventObserver $observer * @return $this */ public function __construct( JsonSerializer $jsonSerializer, RequestInterface $request, Session $checkoutSession, \Magento\Quote\Model\Quote\ItemFactory $quoteItemFactory, \Magento\Quote\Model\ResourceModel\Quote\Item $itemResourceModel, \Magento\Quote\Model\QuoteFactory $quoteFactory, \Magento\Quote\Api\CartRepositoryInterface $itemRepository, CustomerCart $cart, \Psr\Log\LoggerInterface $logger ) { $this->_request = $request; $this->jsonSerializer = $jsonSerializer; $this->_checkoutSession = $checkoutSession; $this->quoteItemFactory = $quoteItemFactory; $this->itemResourceModel = $itemResourceModel; $this->quoteFactory = $quoteFactory; $this->itemRepository = $itemRepository; $this->cart = $cart; $this->_logger = $logger; } /** * @param \Magento\Framework\Event\Observer $observer */ public function execute(\Magento\Framework\Event\Observer $observer) { $quoteItem = $observer->getQuoteItem(); $quote = $quoteItem->getQuote(); $product = $quoteItem->getProduct(); $sku = $product->getSku(); if ($this->_request->getFullActionName() == 'checkout_cart_delete') { if($sku == '1244VR') {
foreach ($quote->getAllVisibleItems() as $loop_item) { if($loop_item->getSku() == '1244VR-1') { $itemId = $loop_item->getItemId(); $this->cart->removeItem($itemId)->save(); } } } } } }
0 Comments On "Magento2 Events After add/remove products from cart and add new products into cart based on the cart items"

Back To Top