1

I want to duplicate configurable Products with their associated products programmatically in Magento. Can anyone help regarding this.

3

You can try this code.

$productId = 2;

//Load configurable product
$product = Mage::getModel('catalog/product')->load($productId);

//Getting children ids
$childs = Mage::getResourceSingleton('catalog/product_type_configurable')
            ->getChildrenIds($productId);

$newChildIds = array();
foreach ($childs as $childId) {
    //duplicate child products
    $newChildProduct = Mage::getModel('catalog/product')->load($childId)->duplicate();
    $newChildIds[] = $newChildProduct->getId();
}

//Duplicate configurable product
$newProduct = $product->duplicate();

//Attach simple products to new configurable
Mage::getResourceSingleton('catalog/product_type_configurable')
    ->saveProducts($newProduct, $newChildIds);

But after duplication of product, new product will be disabled and without SKU. You can enable it and generate SKU for new product added this code:

$newProduct->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
    ->setSku('new_sku');

$newProduct->getResource()->save($newProduct);

EDIT

Try this code for copying attributes (it save attributes):

//Get product attributes
$usedProductAttributeIds = $product->getTypeInstance()->getUsedProductAttributeIds();
$configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();

//Remove some items from attributes
foreach ($configurableAttributesData as $key => $data) {
    unset($configurableAttributesData[$key]['id'], $configurableAttributesData[$key]['values'][0]['value_index']);
}

And after all operations with new product add this code:

$newProductId = $newProduct->getId();

//I dont know, but product must be reloaded.
$newProduct = Mage::getModel('catalog/product')->load($newProductId);    

//Set all attributes
$newProduct->getTypeInstance()->setUsedProductAttributeIds($usedProductAttributeIds);
$newProduct->setConfigurableAttributesData($configurableAttributesData);
$newProduct->setCanSaveConfigurableAttributes(true);

$newProduct->save();

Hope this helps

  • Thanks for the Answer Irop, But how to set the attributes for the Duplicated base product. – user2520 May 20 '16 at 5:03
  • Sorry, I didn't notice that attributes are missing. I'm updated answer. It work for me – Ігор Климчук May 20 '16 at 11:15
  • HI Irop, Do you have any Idea on Duplicating the Bundle products with their Items. – user2520 May 20 '16 at 12:36
  • I duplicated bundle products earlier and i use just $product->duplicate(); and its copy all products data with their items. It does not work for you? – Ігор Климчук May 20 '16 at 13:17
  • When I use $product->duplicate(); it duplicating only the Base product not the bundled items. – user2520 May 23 '16 at 5:54

Your Answer

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