2

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

  • via programmatically ? – zed Blackbeard Nov 15 '17 at 7:19
  • yes. via programmatically. – Haze Nov 15 '17 at 7:20
  • is setConfigurableProductsData() function work in magento 2 ? – Haze Nov 15 '17 at 7:24
4

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($assocIds); // Setting Associated Products
    $configurable_product->setCanSaveConfigurableAttributes(true);
    $configurable_product->save();
} catch (Exception $e) {
    echo "<pre>";
    print_r($e->getMessage());
    exit;
}
| improve this answer | |
  • sorry... it is not work form me. – Haze Nov 15 '17 at 9:39
  • can you add the code ? – zed Blackbeard Nov 15 '17 at 10:23
3

Finally I refer to https://github.com/magento/magento2/blob/2.1/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php and it work!!

| improve this answer | |
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);




?>
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.