How to Add Magento 2 Configurable Products Programmatically to Cart
A quick method for developers who get bored to check the functionalities they implement! (including me 😉)
I was working on a module development task that required to check each and every feature with a simple product and configurable product. Each time repeating the process to select the options, add to cart, and checkout was not feasible.
Hence, I came up with a solution that allowed me to add Magento 2 configurable products programmatically to cart which reduced my tedious task!
Sharing the solution for my readers,
Steps to Add Magento 2 Configurable Products Programmatically to Cart:
- Create registration.php file in app\code\[Vendor]\[Namespace]\
1 2 3 4 5 6 7 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, '[Vendor]_[Namespace]', __DIR__ ); |
2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc
1 2 3 4 5 6 7 |
<?php <?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> |
3. Create Data.php file in app\code\[Vendor]\[Namespace]\Helper
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 getAddConfigurableProduct($parentId, $childId) { $parent = $this->productFactory->load($parentId); $child = $this->productFactory->load($childId); $cart = $this->cart; $params = []; $params['product'] = $parent->getId(); $params['qty'] = '1'; $options = []; $productAttributeOptions = $parent->getTypeInstance(true)->getConfigurableAttributesAsArray($parent); foreach ($productAttributeOptions as $option) { $options[$option['attribute_id']] = $child->getData($option['attribute_code']); } $params['super_attribute'] = $options; /*Add product to cart */ $cart->addProduct($parent, $params); $cart->save(); } } |
You can use the above helper method by passing parent product id and child product id in anywhere in Magento 2.
That’s it.
Whenever you are required to add configurable products to the cart while Magento 2 development, you may use this programmatic method!
Bookmark this post and save yourself from the tiresome task forever!
Hope it helps. You may use the Comments section below to mention the doubts on the topic.
Thank you!