Back to Top

Magento2 – Assign Associated Products To Configurable Product

Updated 16 July 2021

Assign Associated Products To Configurable Product

Use the following code snippet to assign already created associated products to configurable product.

$productId = 12; // Configurable Product Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array(134, 135); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array(2,4,5,6); //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);
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->save();

Note : If there is already associated product assigned (same combination) to configurable product. It will throw error.

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


10 comments

  • Milind
  • Apktech Company
  • Ramazan BOSTAN
  • Sadeesh Mani
  • avvishnu
    • Rahul
      • avvishnu
        • Webkul Support
      • avvishnu
      • avvishnu
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home