Magento2 - How to add a product into cart programatically when checkout_cart_product_add_after is fired
For all those who might waste their day in future, please note below answer which will be helpful to you.
The above code to add product into cart works fine. However the problem is with the logic. I will explain it below.
First of all I was trying to add a product on event checkout_cart_product_add_after
. This event is fired when product is added to the cart.
Further digging into code, if you goto execute function. The code for adding the product into cart is: $this->_cart->addProduct($_product,$params);
If you check addProduct
function in vendor/module-checkout/Model/Cart.php
you will see it is the function which is dispatching checkout_cart_product_add_after
event.
Hence, in our case the control will again return to the observer file which will again try to add product into cart. Recursion will be created which will run until the quantity of our product exhaust.
Once the quantity is exhausted it will stop. Now what we need to do is, add a condition to stop this recursion. The condition can be as per your logic.
Now each time a product is added to cart $product->getId()
will return the latest product added. You can use this to put condition.
In the end my code look something like below:
<?php
namespace MyModule\Applicationcharges\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class AddCharges implements ObserverInterface
{
protected $_productRepository;
protected $_cart;
protected $formKey;
public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart, \Magento\Framework\Data\Form\FormKey $formKey){
$this->_productRepository = $productRepository;
$this->_cart = $cart;
$this->formKey = $formKey;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$item = $observer->getEvent()->getData('quote_item');
$product = $observer->getEvent()->getData('product');
$item = ($item->getParentItem() ? $item->getParentItem() : $item);
// Enter the id of the prouduct which are required to be added to avoid recurrssion
if($product->getId() != 2056){
$params = array(
'product' => 2056,
'qty' => $product->getQty()
);
$_product = $this->_productRepository->getById(2056);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
}
}
}