Sometimes, Magento 2 store admin needs to prefill the shopping cart with a product whenever a user lands to the website. There are many uses of this functionality; for example, the admin may require to add a virtual product to cart whenever a particular product is added to the cart by a customer, the admin may want to give away the free product by default, the admin requires to integrate a custom system or he may require to send visitors directly to the checkout with the product in the cart.
Default Magento 2 doesn’t allow this. So, I’ve come up with a method to programmatically add product to cart in Magento 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php namespace Vendor\Extension\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\Product; class Post extends Action { protected $formKey; protected $cart; protected $product; public function __construct( Context $context, FormKey $formKey, Cart $cart, Product $product) { $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $productId =10; $params = array( 'form_key' => $this->formKey->getFormKey(), 'product' => $productId, 'qty' =>1 ); $product = $this->product->load($productId); $this->cart->addProduct($product, $params); $this->cart->save(); } } |
Run the above code and your task is done in a blink of an eye! Please let me know in the comment section if everything worked as expected. I would be happy to help if you stuck somewhere.
If you think this code saved you time, rate the post with 5 stars 😊
Thank You!