1
    $configurableProduct = $this->_objectManager->create('\Magento\Catalog\Model\Product');
    $configurableProduct->setSku($sku);
    $configurableProduct->setName($name);
    $configurableProduct->setAttributeSetId(4);
    $configurableProduct->setStatus(1);
    $configurableProduct->setTypeId('configurable');
    $configurableProduct->setWebsiteIds(array(1));
    $configurableProduct->setCategoryIds(array(4));
    $configurableProduct->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'is_in_stock' => 1, //Stock Availability
        )
    );
    $configurableProduct->save();

    $productId = $configurableProduct->getId(); // 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(160); // Super Attribute Ids Used To Create Configurable Product
    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->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
    $product->setCanSaveConfigurableAttributes(true);
    $product->save();

This is what I've done so far and the products are created successfully.

But the problem is that, when I view the configurable products, there are no associated products in the panel Configurable products. What did I do wrong? Please help me to fix this problem.

Thanks in advance!

  • I realize that there is a link between configurable product and simple product in catalog_product_relation table. But in the catalog_product_super_attribute table, there is no reference with the product and the attribute. I think that it's the problem. But I don't know how to link it programmatically. Can anyone give me the instruction on how to do that? Thanks a lot! – Tyler Bean Jan 17 '17 at 9:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.