Programmatically Create Configurable Product in Magento 2 Simplified

If you are here, then you are a beginner in Magento 2 world! Welcome. It isn’t as hard as people say

Magento 2 configurable product is a single product with variations in it. Each variation is an individual simple product with a unique SKU. Hence, one can track the inventory for each variation.

There are six product types in Magento 2:

  1. Simple Product
  2. Configurable Product
  3. Grouped Product
  4. Virtual Product
  5. Bundle Product
  6. Downloadable Product

Learning how to programmatically create configurable product in Magento 2 makes it easy for the developers while creating an online store.

For example, apparel available in different sizes or colors is an example of a configurable product.

Check the below code to become a pro in creating Magento 2 configurable products!

Method to programmatically create configurable product in Magento 2:

<?php
namespace [Vendor]\[Module]\Controller;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Catalog\Model\Product;
class Test extends Action
{
    protected $customerSession;
    protected $resultPageFactory;
    protected $redirectFactory;
    protected $newProduct;
    public function __construct(Context $context, Product $newProduct, \Magento\Framework\ObjectManagerInterface $objectManager)
    {
        $this->newProduct = $newProduct;
        parent::__construct($context);

    }
    public function execute()
    {
        $product = $this->newProduct;
        $product->setSku('mySku'); // Set your sku here
        $product->setName('Sample Configurable Product'); // Name of Product
        $product->setAttributeSetId(4); // Attribute set id
        $product->setStatus(1); // Status on product enabled/ disabled 1/0
        $product->setWeight(10); // weight of product
        $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
        $product->setTaxClassId(0); // Tax class id
        $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
        $product->setPrice(100); // price of product
        $product->setStockData(array('use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 999999999));
        $product->save();
    }
}

That’s it. Also in Magento 2 you can get simple product ID from configurable product to get child product ID of a configurable product by swatch options using jQuery.

Easy, ain’t it?

Do share the post with fellow Magento beginners via social media.

Thanks.

Table of Contents