Add a product to a customer cart programatically magento 2
Where you add products depends if you are using a controller or not.
But all you need is the Product Model and the Qty
With product module i mean a loaded Magento\Catalog\Model\Product
. You can use Magento\Catalog\Api\ProductRepositoryInterface
to get it with the sku
or id
of the product.
Do not use Magento\Checkout\Model\Cart
as it is deprecated
Once you have done that use use Magento\Quote\Model\Quote::addProduct()
For example
...
use Magento\Quote\Model\QuoteFactory;
use Magento\Quote\Api\CartRepositoryInterface;
...
public function __construct(
...
QuoteFactory $quote,
CartRepositoryInterface $cartRap
...
){
...
$this->quote = $quote;
$this->cartRep = $cartRap;
...
}
...
function ... ()
{
...
try {
// if you need to get the quote by customerid
$quote = $this->cartRep->getActiveForCustomer($customerid);
// then load it
$cart = $this->quote->create()->loadActive($quote->getId());
$cart->addProduct($product, $qty);
$cart->save();
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
...
}
You can use like this:-
<?php
namespace MyModule\AddToCart\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class AddToCart 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() != 5){
$params = array(
'product' => 5,
'qty' => $product->getQty()
);
$_product = $this->_productRepository->getById(5);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
}
}
}
I hope it's work.. And you can take more details Here
You can take also Here for more details.