Magento – Magento 2 add simple products to configurable products

configurable-productmagento-2.1.7

I am having trouble associating a newly created simple product to an existing configurable product that already have simple products associated.

Using the code below, it will delete the existing simple products associated to the configurable product and add the new one. I want to keep the old simple products associated with the configurable product.

$product = $this->productRepository->get($sku);
$product->setAssociatedProductIds($new_simple_product_ids);
$this->productRepository->save($product);

I also seems that if configurable products doesn't have any simple products yet it will fail with this error:

[Magento\Framework\Exception\InputException] Option values are not specified.

I have tried going through different approaches it this seems the closes but I am unsure how it applies to my problem:

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

Best Answer

If the configurable has no simples associated yet it doesn't even have attributes selected to connect those simples by. That's why it's breaking.

To add new simple to configurable take a look at \Magento\ConfigurableProduct\Model\LinkManagement::addChild()

It is taking all values from configurable, then just adds them again with the new one included.

Related Topic