i am using the below code to create a configurable product from product sku (from attributes color and size), it is working fine when all associated products have both attributes - color and size
Issue comes one Attribute is not there in all associated product.
For eg
Case 1: works fine
SKU 1 : Size - L and Color - Red
SKU 2 : Size -M and Color - Black
Case 2: Add to cart not working as both associated product have one attribute Color missing as both associated product
SKU 1 : Size - L
SKU 2 : Size -M
Case 3: Add to cart not working as both associated product have one attribute Size missing as both associated product
SKU 1 : Color - Red
SKU 2 : Color - Black
Also i get the below error in the admin when I try to edit the configurable product in CASE 2 and CASE 3
Notice: Undefined offset: 0 in /usr/share/nginx/zodiac/html/vendor/magento/module-configurable-product/Model/Product/Type/VariationMatrix.php on line 49
Exception in /usr/share/nginx/zodiac/html/vendor/magento/framework/App/ErrorHandler.php:61
Code as below :
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->setTypeId('configurable')
->setStatus(1) // 1 = enabled, 2 = disabled
->setAttributeSetId(4) // 4 = default
->setName('Configurable test product')
->setSku('config')
->setPrice(0)
->setTaxClassId(2) // 0 = None, 2 = Default product tax class
->setCategoryIds(array(2)) // 2 = Default category
->setDescription('test description')
->setShortDescription('test short description')
->setUrlKey('configurable-test-product')
->setWebsiteIds(array(1)) // 1 = Default Website ID
->setStoreId(0) // 0 = Default store ID
->setVisibility(4); // 4 = Catalog & Search
$product_resource = $product->getResource();
$color_attribute = $product_resource->getAttribute('color');
$size_attribute = $product_resource->getAttribute('size');
$color_attribute_id = $color_attribute->getId();
$size_attribute_id = $size_attribute->getId();
$configurable_attributes = array('color', 'size'); // put here all configurable attributes you need and get their attribute IDs like I showed above
$product->getTypeInstance()->setUsedProductAttributeIds(array($color_attribute_id, $size_attribute_id), $product); // assign attributes to configurable product
$configurable_attributes_data = $product->getTypeInstance()->getConfigurableAttributesAsArray($product);
$product->setCanSaveConfigurableAttributes(true);
$product->setConfigurableAttributesData($configurable_attributes_data);
$child_product_skus = array('SKU1','SKU2');
$child_ids = array();
foreach ($child_product_skus as $child_product) {
echo "<br>".$child_product;
$child_ids[] = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($child_product);
}
print_r($child_ids);
$product->setAssociatedProductIds($child_ids);
$product->save();