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.
It is not working.
Created simple products for one attributes options. There is no error but in admin, Configurations section is empty.