Welcome TO magento1 and magento2 store market
How to Add Product to Cart Programmatically With Custom Options in Magento 2
Earlier, I showed you How to Add Magento 2 Configurable Products Programmatically to Cart
Now, what if you are required to add product to cart programmatically with custom options in Magento 2 ?
Crazy business requirements, isn’t it? 😰
I get you, fellow developers 😄
Moreover, this solution can also be helpful if you want an automatic “add to cart” functionality for the configurable product with custom options. For example, the store is offering a free product with a particular product, attach a warranty, or add a gift product!
But what if such products you are adding to the Magento 2 cart are the configurable product! And, if that was not enough, they have custom options too! It can be a bit tricky.
Create registration.php file in app\code\[Vendor]\[Namespace]\
1 2 3 4 5 6 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, '[Vendor]_[Namespace]', __DIR__ ); |
Create module.xml file in app\code\[Vendor]\[Namespace]\etc
1 2 3 4 5 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="[Vendor]_[Namespace]" setup_version="1.0.0"/> </config> |
Here’s the solution for the same:
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 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php namespace [Vendor]\[namespace]\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\ProductFactory; class Data extends AbstractHelper { private $cart; private $productFactory; public function __construct(Context $context, Cart $cart, ProductFactory $productFactory) { $this->productFactory = $productFactory; $this->cart = $cart; parent::__construct($context); } public function getAddCustomProduct($productId) { $product = $this->productFactory->load($productId); $cart = $this->cart; $params = array(); $options = array(); $params['qty'] = 1; $params['product'] = $productId; foreach ($product->getOptions() as $o) { foreach ($o->getValues() as $value) { $options[$value['option_id']] = $value['option_type_id']; } } $params['options'] = $options; $cart->addProduct($product, $params); $cart->save(); } } |