Programmatically (manually) creating Configurable Magento 2 Product

4k views Asked by At

Programmatically (manually) creating Configurable Magento 2 Product :

The Product are generated correctly, but I am facing issue with, not generating product Configuration Details.

This Configuration details will help to generate the relation between Configurable product and associate Child Products, these part not working while programmatically create the Product.

Please suggest solution for this issue.

Please find my below code:

<?php 
ini_set("display_errors",1);
$magentoDirPath=dirname(dirname(__FILE__)); 
use \Magento\Framework\App\Bootstrap;
include($magentoDirPath.'/app/bootstrap.php');  //   File Path 

// add bootstrap
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();

$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

//simple product
$simple_product = $object_Manager->create('\Magento\Catalog\Model\Product');
$simple_product->setSku('test-simple-randdd');
$simple_product->setName('test name simple');
$simple_product->setAttributeSetId(4);
$simple_product->setColor(4); // value id of S size
$simple_product->setStatus(1);
$simple_product->setTypeId('simple');
$simple_product->setPrice(10);
$simple_product->setWebsiteIds(array(1));
$simple_product->setCategoryIds(array(4,5));
$simple_product->setStockData(array(
    'use_config_manage_stock' => 0, //'Use config settings' checkbox
    'manage_stock' => 1, //manage stock
    'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
    'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
    'is_in_stock' => 1, //Stock Availability
    'qty' => 100 //qty
    )
);

$simple_product->save();

$simple_product_id = $simple_product->getId();
echo "simple product id: ".$simple_product_id."\n";

//configurable product
$configurable_product = $object_Manager->create('\Magento\Catalog\Model\Product');
$configurable_product->setSku('test-configurable');
$configurable_product->setName('test name configurable');
$configurable_product->setAttributeSetId(4);
$configurable_product->setColor(4); // value id of S size
$configurable_product->setStatus(1);
$configurable_product->setTypeId('configurable');
$configurable_product->setPrice(11);
$configurable_product->setWebsiteIds(array(1));
$configurable_product->setCategoryIds(array(4,5));
$configurable_product->setStockData(array(
   'use_config_manage_stock' => 0, //'Use config settings' checkbox
    'manage_stock' => 1, //manage stock
    'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
    'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
    'is_in_stock' => 1, //Stock Availability
    'qty' => 100 //qty
    )
);
$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(93),$configurable_product); //attribute ID of attribute 'size_general' in my store
$configurableAttributesData = $configurable_product->getTypeInstance()->getConfigurableAttributesAsArray($configurable_product);

$configurable_product->setCanSaveConfigurableAttributes(true);
$configurable_product->setConfigurableAttributesData($configurableAttributesData);



$configurableProductsData = array();
$configurableProductsData[$simple_product_id] = array( 
    '0' => array(
        'label' => 'Color', //attribute label
        'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
        'value_index' => '4', //value of 'S' index of the attribute 'size_general'
        'is_percent'    => 0,
        'pricing_value' => '10',
    )
);

// 1 - Static ID of Product

$configurableProductsData['1'] = array(             
    '0' => array(
        'label' => 'Color', //attribute label
        'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
        'value_index' => '5', //value of 'S' index of the attribute 'size_general'
        'is_percent'    => 0,
        'pricing_value' => '10',
    )
);

// 91 - Static ID of Product
$configurableProductsData['91'] = array( 
    '0' => array(
        'label' => 'Color', //attribute label
        'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
        'value_index' => '6', //value of 'S' index of the attribute 'size_general'
        'is_percent'    => 0,
        'pricing_value' => '10', ini_set("display_errors",1);

        $magentoDirPath=dirname(dirname(__FILE__)); 
        use \Magento\Framework\App\Bootstrap;
        include($magentoDirPath.'/app/bootstrap.php');  //   File Path 



        // add bootstrap
        $bootstraps = Bootstrap::create(BP, $_SERVER);
        $object_Manager = $bootstraps->getObjectManager();

        $app_state = $object_Manager->get('\Magento\Framework\App\State');
        $app_state->setAreaCode('frontend');


        //simple product
        $simple_product = $object_Manager->create('\Magento\Catalog\Model\Product');
        $simple_product->setSku('test-simple-randdd');
        $simple_product->setName('test name simple');
        $simple_product->setAttributeSetId(4);
        $simple_product->setColor(4); // value id of S size
        $simple_product->setStatus(1);
        $simple_product->setTypeId('simple');
        $simple_product->setPrice(10);
        $simple_product->setWebsiteIds(array(1));
        $simple_product->setCategoryIds(array(4,5));
        $simple_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 100 //qty
            )
        );

        $simple_product->save();

        $simple_product_id = $simple_product->getId();
        echo "simple product id: ".$simple_product_id."\n";

        //configurable product
        $configurable_product = $object_Manager->create('\Magento\Catalog\Model\Product');
        $configurable_product->setSku('test-configurable');
        $configurable_product->setName('test name configurable');
        $configurable_product->setAttributeSetId(4);
        $configurable_product->setColor(4); // value id of S size
        $configurable_product->setStatus(1);
        $configurable_product->setTypeId('configurable');
        $configurable_product->setPrice(11);
        $configurable_product->setWebsiteIds(array(1));
        $configurable_product->setCategoryIds(array(4,5));
        $configurable_product->setStockData(array(
           'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 100 //qty
            )
        );

        $configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(93),$configurable_product); //attribute ID of attribute 'size_general' in my store
        $configurableAttributesData = $configurable_product->getTypeInstance()->getConfigurableAttributesAsArray($configurable_product);

        $configurable_product->setCanSaveConfigurableAttributes(true);
        $configurable_product->setConfigurableAttributesData($configurableAttributesData);

        $configurableProductsData = array();
        $configurableProductsData[$simple_product_id] = array( 
            '0' => array(
                'label' => 'Color', //attribute label
                'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
                'value_index' => '4', //value of 'S' index of the attribute 'size_general'
                'is_percent'    => 0,
                'pricing_value' => '10',
            )
        );

        // 1 - Static ID of Product

        $configurableProductsData['1'] = array(             
            '0' => array(
                'label' => 'Color', //attribute label
                'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
                'value_index' => '5', //value of 'S' index of the attribute 'size_general'
                'is_percent'    => 0,
                'pricing_value' => '10',
            )
        );

        // 91 - Static ID of Product
           $configurableProductsData['91'] = array( 
            '0' => array(
                'label' => 'Color', //attribute label
                'attribute_id' => '93', //attribute ID of attribute 'size_general' in my store
                'value_index' => '6', //value of 'S' index of the attribute 'size_general'
                'is_percent'    => 0,
                'pricing_value' => '10',
            )
        );

        $configurable_product->setConfigurableProductsData($configurableProductsData);

        $associatedProductIds =array($simple_product_id,'1','91'); 
        $configurable_product->setCanSaveConfigurableAttributes(true);
        $configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(93), $configurable_product);
        $configurable_product->setNewVariationsAttributeSetId($configurable_product->getAttributeSetId());
        $configurable_product->setAssociatedProductIds($associatedProductIds);
        $configurable_product->setConfigurableAttributesData($configurableAttributesData);


        $configurable_product->save();
        $configProductId = $configurable_product->getId();

        echo "Product id: ".$configurable_product->getId()."\n";

        exit;
    )
);

$configurable_product->setConfigurableProductsData($configurableProductsData);

$associatedProductIds =array($simple_product_id,'1','91'); 
$configurable_product->setCanSaveConfigurableAttributes(true);
$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array(93), $configurable_product);
$configurable_product->setNewVariationsAttributeSetId($configurable_product->getAttributeSetId());
$configurable_product->setAssociatedProductIds($associatedProductIds);
$configurable_product->setConfigurableAttributesData($configurableAttributesData);

$configurable_product->save();
$configProductId = $configurable_product->getId();

echo "Product id: ".$configurable_product->getId()."\n";

exit;
?>
1

There are 1 answers

0
Jakub Ilczuk On

must be done by product repository

working code below

ids of simples are defined here: $associatedProductIds=array(2042, 2044); attribute is color, must be in default attribute set, can be more then 1 if you duplicate attributeValues array and add it here: $configurableAttributesData = []

$ob = ObjectManager::getInstance();

/** @var $installer \Magento\Catalog\Setup\CategorySetup */
$installer = $ob->create('Magento\Catalog\Setup\CategorySetup');

/** @var ProductRepositoryInterface $productRepository */
$productRepository = $ob->create(ProductRepositoryInterface::class);
/** @var $installer CategorySetup */
$installer = $ob->create(CategorySetup::class);
/* Create simple products per each option value*/
/** @var AttributeOptionInterface[] $options */
$attributeSetId = $installer->getAttributeSetId('catalog_product', 'Default');


$eavConfig = $ob->get('Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');

$options = $attribute->getOptions();
array_shift($options); //remove the first option which is empty

$attributeValues = [];



foreach ($options as $option) {
    $attributeValues[] = [
        'label' => 'test',
        'attribute_id' => $attribute->getId(),
        'value_index' => $option->getValue(),
    ];
}

$associatedProductIds=array(2042, 2044);


/** @var Factory $optionsFactory */
$optionsFactory = $ob->create(Factory::class);
$configurableAttributesData = [
    [
        'attribute_id' => $attribute->getId(),
        'code' => $attribute->getAttributeCode(),
        'label' => $attribute->getStoreLabel(),
        'position' => '0',
        'values' => $attributeValues,
    ],
];

/** @var $product Product */
$product = $ob->create(Product::class);

$configurableOptions = $optionsFactory->create($configurableAttributesData);

$extensionConfigurableAttributes = $product->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);

$product->setTypeId(Configurable::TYPE_CODE)
    ->setAttributeSetId($attributeSetId)
    ->setWebsiteIds([1])
    ->setName('Connewfcolor')
    ->setSku('configcolor')
    ->setVisibility(Visibility::VISIBILITY_BOTH)
    ->setStatus(Status::STATUS_ENABLED)
    ->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($product);