Olli Bolli Olli Bolli - 1 year ago 89
PHP Question

Attach simple products to a configurable product programmatically

I am trying to join some existing simple products programmatically to an existing configurable product.

I hardly found any hints / documentation on this. I examined the MAGMI Magento Mass Importer Plugin (in particular the

-file) with no success.

After that I found this snippet:

function attachProductToConfigurable($childProduct, $configurableProduct)
$loader = Mage::getResourceModel('catalog/product_type_configurable')
->load($configurableProduct, $configurableProduct->getId());

$ids = $configurableProduct

$newids = array();
foreach ($ids as $id) {
$newids[$id] = 1;
$newids[$childProduct->getId()] = 1;

//$loader->saveProducts( $_configurableProduct->getid(), array_keys( $newids ) );
$loader->saveProducts($configurableProduct, array_keys($newids));

But when I am trying to call the function like this:

$sProduct = Mage::getModel('catalog/product')
->loadByAttribute('sku', $v);
$cProduct = Mage::getModel('catalog/product')
->loadByAttribute('sku', $sku);
attachProductToConfigurable($sProduct, $cProduct);

(each simple product SKU gets passed step by step to the configurable product)

Fatal error: Call to a member function getId() on a non-object in ... on line 1018

which is this line from the function itself

$loader = Mage::getResourceModel('catalog/product_type_configurable')
->load($configurableProduct, $configurableProduct

Since I do not find anything similar to joining simple SKUs to an existing configurable product, I am stuck looking up what might be wrong upon initializing the function calls, resource models etc..

Any ideas on what to keep an eye on to get this going are highly appreciated.

Answer Source

Give this a try:

    ->saveProducts($mainConfigrableProduct, $simpleProductIds);

Where $mainConfigrableProduct must be an instance of the configurable product, and $simpleProductIds is an array with the ids of the simple products associated to the configurable products.

On a side note, be very careful when doing this. The simple products must be in the same attribute set as the configurable products. Here is what can happen if they are not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download