Add Product in Cart Programmatically from observers, blocks, helper, plugin etc.
There are just few lines of code to add a product in cart using cart model.
Write the following code in the function of your class of (observer, block, helper, plugin) to add product in cart.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get(
'Magento\Checkout\Model\Cart'
);
$productRepo = $objectManager->get(
'Magento\Catalog\Model\ProductRepository'
);
$productData = [];
$productData['qty'] = PRODUCT_QUANTITY; // input here for quantity of product, for. e.g : 5
$productData['product'] = PRODUCT_ID; // input product id here, for e.g : 1
$_product = $productRepo->getById(PRODUCT_ID);
if ($_product) {
$cart->addProduct($_product, $productData); // adds product in cart using cart model
}
$cart->save();
$cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
$cart->getQuote()->save();
Be the first to comment.