Magento2 – Associate Simple Product to Configurable Product

configurable-productcustom-optionsmagento2

I need to import 40,000 product from xls so that reason I wrote an importer, I already did for magento 1.x but we switch our web site magento 2,
I can create simple and configurable product programatically but I cant associate simple product to configurable product, This is the best documentation I followed,

Programmatically create a configurable product and assign the simple product to configurable product in Magento2 product

But I stuck configurable product options always throw an error,

Call to a member function getId() on array in .../vendor/magento/module-configurable-product/Model/Plugin/AroundProductRepositorySave.php on line 109

Here is my code,

$configurableProductOptions = [
[
"attribute_id" =>  137,
"label" => 'size',
"position" => 0,
"values" => [
[
"value_index" =>  333,
],
[
"value_index" =>  334,
]
],
]
];

$product->setCanSaveConfigurableAttributes(true);
$product->setCanSaveCustomOptions(true);
$productExtensionFactory= $objectManager->create('\Magento\Catalog\Api\Data\ProductExtensionFactory');
$productExtension = $productExtensionFactory->create();
$productExtension->setConfigurableProductLinks($sipmle_product_ids);
$productExtension->setConfigurableProductOptions([
                                                $configurableProductOptions
                                                 ]);
$product->setExtensionAttributes($productExtension);
$productRepository = $objectManager->create(Magento\Catalog\Api\ProductRepositoryInterface::class);

$productRepository->save($product,true);

I m totaly sure something wrong in '$configurableProductOptions' tried almost everything but didnt succeed any ideas or anyone can share code to associate simple product as a configurable I can figured out from that code.

Best Answer

Looks like you need to add StockItem extension attribute to your configurable product.

See how Magento developer do it in the test fixture product_configurable.php

Related Topic