Skip to content

How to create Product with options (Configurable Product) in Magento 2

Hi I am newbie in Magento, I am creating product with options. I am able to create simple product but I am confused with how to create attributes and options. I am explaining myself what I have done so far, please let me know if somewhere I have to revise.

$productFactory    = $this->_objectManager->get('MagentoCatalogModelProductFactory');
$product = $productFactory->create();

$title = "Configurable Product";
$urlKey = "main-product-url";
$sku = "main-product-sku";
    
$product_obj2              = $this->_objectManager->get('MagentoCatalogModelProduct');
$productCollectionBySku    = $product_obj2->getCollection()->addAttributeToFilter('sku', $sku );

// Check if any product exist with same SKU
if( $productCollectionBySku->getSize() ) {
    $product = $productCollectionBySku->getFirstItem();

}

$product->setName( $title );
$product->setAttributeSetId(4);

// $product->setShortDescription( );
// $product->setDescription( );

$product->setStatus(1);
$product->setWeight(0);

$product->setTaxClassId(0);

$product->setTypeId( "configurable" );
$product->setPrice( 100 );

$product->setVisibility(4); // visible to Catalog, Search

$product->setStockData(
    array(
        'use_config_manage_stock' => 0,
        'manage_stock'            => 1,
        'is_in_stock'             => 1,
        'qty'                     => 999999
    )
);

$product->save();

$configurableProductid = $product->getId();


/**
 * now start inserting product variations
 */

$variations = array(
    array(
        "option_a" => "yes", // can have value Yes or No
        "option_b" => "some other value" // Options can be multiple based on data provided in API. 
        "price" => 100,
        "quantity" => 10
    ),
    array(
        "option_a" => "no", 
        "option_b" => "some other value"
        "price" => 11,
        "quantity" => 10
    )
);

// Check if option_a & option_b attribute is already exist

$entityAttribute = $objectManager->get('MagentoEavModelResourceModelEntityAttribute');
$attributeIdOptionA = $entityAttribute->getIdByCode('catalog_product', "option_a"); // Not tested.
$attributeIdOptionB = $entityAttribute->getIdByCode('catalog_product', "option_b");

// How do I insert option values to above attributes? Need help here...



// Create simple product with variation options
foreach( $variations as $key => $variation ) {
    $title = "Configurable Product"; // Same product title as of the parent product
    $urlKey = "main-product-url"; // I am gussing same product URL should work but if not I can change it to something else
    $sku = "main-product-sku-". $variation["option_a"] ."-". $variation["option_b"];
        
    $product_obj2              = $this->_objectManager->get('MagentoCatalogModelProduct');
    $productCollectionBySku    = $product_obj2->getCollection()->addAttributeToFilter('sku', $sku );

    // Check if any product exist with same SKU
    if( $productCollectionBySku->getSize() ) {
        $product = $productCollectionBySku->getFirstItem();

    }

    $simpleProduct->setName( $title );
    $simpleProduct->setAttributeSetId(4);

    // $product->setShortDescription( );
    // $product->setDescription( );
    
    $simpleProduct->setStatus(1);
    $simpleProduct->setWeight(0);

    $simpleProduct->setTaxClassId(0);
    
    $simpleProduct->setTypeId( "simple" );
    $simpleProduct->setPrice( $variation["price"] );

    $simpleProduct->setVisibility(1); // not visible individually

    $simpleProduct->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock'            => 1,
            'is_in_stock'             => 1,
            'qty'                     => 999999
        )
    );

    $simpleProduct->save();

    $productVariationIds[] = $simpleProduct->getId();
}


$attributeModel = $this->_objectManager->create('MagentoConfigurableProductModelProductTypeConfigurableAttribute');

$position = 0;

// How do I get attribute Ids? Does $entityAttribute->getIdByCode('catalog_product', "option_a") will work? Or something else
$attributes = array(134, 135); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = $productVariationIds; //Product Ids Of Associated Products

foreach ($attributes as $attributeId) {
    $data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position);
    $position++;
    $attributeModel->setData($data)->save();
}

$product->setTypeId('configurable'); // Setting Product Type As Configurable
$product->setAffectConfigurableProductAttributes(4);

$this->_objectManager->create('MagentoConfigurableProductModelProductTypeConfigurable')->setUsedProductAttributeIds($attributes, $product);

$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->save();