Consider there are two product ie: Product A and Product B. Product B is a virual product which i need to add to cart when Product A is added to it.
To do so, I am trying to add Product B to cart by observing an event checkout_cart_product_add_after
. Once Product A is added, i am retrieving the quantity of product added for Product A and based on it I am trying to add Product B programatically. To add product B, I have written below code:
<?php
namespace MyModule\Applicationcharges\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class AddCharges implements ObserverInterface
{
protected $_productRepository;
protected $_cart;
public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart){
$this->_productRepository = $productRepository;
$this->_cart = $cart;
}
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 );
$product->getQty();
$params = array(
'product' => 2056,
'qty' => 1
);
$_product = $this->_productRepository->getById(2056);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
}
}
However, trying to add product using $this->_cart->addProduct()
doesn't work. Can anyone please guide how this can be done? Is there anything which I am missing.
Any guidance will be appreciated.