Attach simple products to a configurable product programmatically
Asked Answered
G

1

7

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 magmi_productimportengine.php-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
        ->getTypeInstance()
        ->getUsedProductIds();

    $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
              ->getId());

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.

Gilly answered 25/4, 2014 at 7:59 Comment(0)
S
22

Give this a try:

Mage::getResourceSingleton('catalog/product_type_configurable')
    ->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.

Sottish answered 25/4, 2014 at 8:13 Comment(1)
Hi Marius, thank you again! Merging SKUs this way does work without an error. As you mentioned i have to get the attribute sets right now. Thank you too for pointing out the danger in this! :-) All the bestGilly

© 2022 - 2024 — McMap. All rights reserved.