3

I want to create a configurable product and assign some simple product to it. I have found lots of solution in the web but it's not working. Please let me know if any idea!!!

Thanks

Aasim Goriya
5,4622 gold badges30 silver badges54 bronze badges
asked Nov 15, 2017 at 7:12
3
  • via programmatically ? Commented Nov 15, 2017 at 7:19
  • yes. via programmatically. Commented Nov 15, 2017 at 7:20
  • is setConfigurableProductsData() function work in magento 2 ? Commented Nov 15, 2017 at 7:24

4 Answers 4

7

This code has worked for me. it may be help you.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configurable_product = $objectManager->create('\Magento\Catalog\Model\Product');
$configurable_product->setSku('CONFIG_SKU'); // set sku
$configurable_product->setName('CONFIG PRODUCT NAME'); // set name
$configurable_product->setAttributeSetId(4);
$configurable_product->setStatus(1);
$configurable_product->setTypeId('configurable');
$configurable_product->setPrice(0);
$configurable_product->setWebsiteIds(array(1)); // set website
$configurable_product->setCategoryIds(array(2)); // set category
$configurable_product->setStockData(array(
 'use_config_manage_stock' => 0, //'Use config settings' checkbox
 'manage_stock' => 1, //manage stock
 'is_in_stock' => 1, //Stock Availability
 )
);
// super attribute 
$size_attr_id = $configurable_product->getResource()->getAttribute('product_size')->getId();
$color_attr_id = $configurable_product->getResource()->getAttribute('color')->getId();
$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array($color_attr_id, $size_attr_id), $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();
$configurable_product->setConfigurableProductsData($configurableProductsData);
try {
 $configurable_product->save();
} catch (Exception $ex) {
 echo '<pre>';
 print_r($ex->getMessage());
 exit;
}
$productId = $configurable_product->getId();
// assign simple product ids
$associatedProductIds = array(12,13,14);
try{
$configurable_product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product
 $configurable_product->setAssociatedProductIds($associatedProductIds); // Setting Associated Products
 $configurable_product->setCanSaveConfigurableAttributes(true);
 $configurable_product->save();
} catch (Exception $e) {
 echo "<pre>";
 print_r($e->getMessage());
 exit;
}
Tirth Patel
1,0498 silver badges27 bronze badges
answered Nov 15, 2017 at 7:37
2
  • sorry... it is not work form me. Commented Nov 15, 2017 at 9:39
  • can you add the code ? Commented Nov 15, 2017 at 10:23
1

This method worked for me on Magento 2.3.5 with attribute codes color and size and presumes that you have already created simple products with color and size options.

$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('1000')
 ->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('1234','2345'); // add all child skus you need
 $child_products = explode(',', $child_product_skus);
 $child_ids = array();
 foreach ($child_products as $child_product) {
 $child_ids[] = $product->getIdBySku($child_product);
 }
 $product->setAssociatedProductIds($child_ids);
 $product->save();
answered Sep 18, 2020 at 16:30
0
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need
// Define Zend Logger
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/create-product.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$simpleProduct = $objectManager->create('\Magento\Catalog\Model\ProductFactory')->create();
$productAttributeRepository = $objectManager->create('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$atributeCode = ['color','size'];
$color = $productAttributeRepository->get('color');
$colorLabel = $color->getData('frontend_label');
$colorOptions = $color->getOptions();
array_shift($colorOptions);
$size = $productAttributeRepository->get('size');
$sizeLabel = $size->getData('frontend_label');
$sizeOptions = $size->getOptions();
array_shift($sizeOptions);
//print_r(json_decode(json_encode($color->getData('frontend_label')),true));die;
$attributeValues = [];
$configurableAttributesData = [];
foreach ($sizeOptions as $sizeOption) {
$sizeAttributeValues[] = [
'label' => $sizeLabel,
'attribute_id' => $size->getId(),
'value_index' => $sizeOption->getValue(),
];
//$sizeAttributeValues[] = $sizeOption->getValue();
}
$configurableAttributesData[] = [
'attribute_id' => $size->getId(),
'code' => $size->getAttributeCode(),
'label' => $size->getStoreLabel(),
'position' => '0',
'values' => $sizeAttributeValues,
];
foreach ($colorOptions as $colorOption) {
$colorAttributeValues[] = [
'label' => $colorLabel,
'attribute_id' => $color->getId(),
'value_index' => $colorOption->getValue(),
];
//$colorAttributeValues[] = $colorOption->getValue();
}
$configurableAttributesData[] =
[
'attribute_id' => $color->getId(),
'code' => $color->getAttributeCode(),
'label' => $color->getStoreLabel(),
'position' => '0',
'values' => $colorAttributeValues,
];
foreach ($sizeOptions as $sizeOption) {
 foreach ($colorOptions as $colorOption) {
$sizeValue = $sizeOption->getValue();
$colorValue = $colorOption->getValue();
//echo "<br> size $sizeValue : Color $colorValue <br>";
$rand = rand(10,100);
$simpleProduct = $objectManager->create(\Magento\Catalog\Model\Product::class);
$attributeSetId = $simpleProduct->getDefaultAttributeSetId();
$simpleProduct->setTypeId('simple')
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('Simple_Product1 - ' . $sizeOption->getLabel(). '-'.$colorOption->getLabel())
->setSku('simple_2' .$sizeOption->getLabel(). '-'.$colorOption->getLabel())
->setPrice(10)
->setColor($colorValue)
->setSize($sizeValue ) // Set the 'color' attribute option value
->setVisibility(1) 
->setStatus(1)
->setWeight(2)
->setCategories('Default')
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$simpleProduct = $productRepository->save($simpleProduct);
$associatedProductIds[] = $simpleProduct->getId();
$msg = 'Created Simple Product. Product ID: ' . $simpleProduct->getId();
echo $msg . '<br />';
$logger->info($msg);
}
}
$optionsFactory = $objectManager->create(\Magento\ConfigurableProduct\Helper\Product\Options\Factory::class);
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$configurableProduct = $objectManager->create(\Magento\Catalog\Model\Product::class);
$extensionConfigurableAttributes = $configurableProduct->getExtensionAttributes();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$rand = rand(10,100);
$configurableProduct->setTypeId('configurable')
//->setId(1)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName('Test Configurable Product1'.$rand)
->setSku('test-configurable-33-'.$rand )
->setUrlKey('test-configurable-22-'.$rand)
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100 ,'is_in_stock' => 1]);
$configurableProduct->setExtensionAttributes($extensionConfigurableAttributes);
$configurableProduct = $productRepository->save($configurableProduct);$msg = 'Created Configurable Product. Product ID: ' . $configurableProduct->getId();
echo $msg . '<br />';
$logger->info($msg);
?>
Savan Patel
2,4541 gold badge19 silver badges43 bronze badges
answered Feb 7, 2020 at 5:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.