Programmatically create a configurable Magento product

Programmatically create a configurable Magento product

I already wrote about creating a simple product programmatically in Magento. For configurable product, however, things get a little bit complicated.

As you already know, a configurable product is merely a product with simple products that differ in some option (attribute) assigned to itself.

We can use this conclusion to extend our code for creation of simple products to work with configurable.

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleProduct = Mage::getModel('catalog/product');
try {
$simpleProduct
// ->setStoreId(1) //you can set data in store scope
->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setAttributeSetId(20) //ID of a attribute set named 'default'
->setTypeId('simple') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
->setSku('simple99y') //SKU
->setName('test simple product99') //product name
->setWeight(4.0000)
->setStatus(1) //product status (1 - enabled, 2 - disabled)
->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setColor(24)
->setNewsFromDate('06/26/2014') //product set as new from
->setNewsToDate('06/30/2014') //product set as new to
->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
->setPrice(11.22) //price in form 11.22
->setCost(22.33) //price in form 11.22
->setSpecialPrice(00.44) //special price in form 11.22
->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
->setMsrpEnabled(1) //enable MAP
->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp(99.99) //Manufacturer's Suggested Retail Price
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
->setDescription('This is a long description')
->setShortDescription('This is a short description')
->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 999 //qty
)
)
->setCategoryIds(array(3, 10)); //assign product to categories
$simpleProduct->save();
} catch (Exception $e) {
Mage::log($e->getMessage());
echo $e->getMessage();
}

The code above would create a simple product. I won’t go into the details, but if you want, you can read more on my previous article by clicking on the link written at the top.

What we need to do now is create a configurable product and assign this simple product to it.

$configProduct = Mage::getModel('catalog/product');,
try {
$configProduct
// ->setStoreId(1) //you can set data in store scope
->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
->setAttributeSetId(20) //ID of a attribute set named 'default'
->setTypeId('configurable') //product type
->setCreatedAt(strtotime('now')) //product creation time
// ->setUpdatedAt(strtotime('now')) //product update time
->setSku('configurable96') //SKU
->setName('test config product96') //product name
->setWeight(4.0000)
->setStatus(1) //product status (1 - enabled, 2 - disabled)
->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setManufacturer(28) //manufacturer id
->setNewsFromDate('06/26/2014') //product set as new from
->setNewsToDate('06/30/2014') //product set as new to
->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
->setPrice(11.22) //price in form 11.22
->setCost(22.33) //price in form 11.22
->setSpecialPrice(00.44) //special price in form 11.22
->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
->setMsrpEnabled(1) //enable MAP
->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
->setMsrp(99.99) //Manufacturer's Suggested Retail Price
->setMetaTitle('test meta title 2')
->setMetaKeyword('test meta keyword 2')
->setMetaDescription('test meta description 2')
->setDescription('This is a long description')
->setShortDescription('This is a short description')
->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'is_in_stock' => 1, //Stock Availability
)
)
->setCategoryIds(array(3, 10)) //assign product to categories
;
/**/
/** assigning associated product to configurable */
/**/
$configProduct->getTypeInstance()->setUsedProductAttributeIds(array(92)); //attribute ID of attribute 'color' in my store
$configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
 
$configProduct->setCanSaveConfigurableAttributes(true);
$configProduct->setConfigurableAttributesData($configurableAttributesData);
 
$configurableProductsData = array();
$configurableProductsData['920'] = array( //['920'] = id of a simple product associated with this configurable
'0' => array(
'label' => 'Green', //attribute label
'attribute_id' => '92', //attribute ID of attribute 'color' in my store
'value_index' => '24', //value of 'Green' index of the attribute 'color'
'is_percent' => '0', //fixed/percent price for this option
'pricing_value' => '21' //value for the pricing
)
);
$configProduct->setConfigurableProductsData($configurableProductsData);
$configProduct->save();
 
echo 'success';
} catch (Exception $e) {
Mage::log($e->getMessage());
echo $e->getMessage();
}

And that’s it! Your configurable product should be properly set up and visible on the frontend!

Note that you need to assign the same attribute set to both configurable product and it’s associated products.

In the code comments you’ll find a short comment for each of the methods used. As in previous article, you can log the saveAction of Mage_Adminhtml_Catalog_ProductController to get list of all the data keys you can add for the product.

Need help following the code in this article? Leave a comment below.

You made it all the way down here so you must have enjoyed this post! You may also like:

Shell script for converting configurable to grouped products Tsvetan Stoychev
Tsvetan Stoychev, | 5

Shell script for converting configurable to grouped products

Programmatically create bundle products in Magento Petar Sambolek
Petar Sambolek, | 5

Programmatically create bundle products in Magento

Programmatically (manually) creating simple Magento product Petar Sambolek
Petar Sambolek, | 40

Programmatically (manually) creating simple Magento product

20 comments

  1. For some reason when i create the configurable product. Its options aren’t showing in the frontend.
    However, if i just click in the save button inside the admin, its options shows.

    I believe something is missing on this guide. (Reindex perhaps?)

  2.  This is running code which i am using for configurable product.
    Here configurable product is using three attribute for color shape and color.
    attributes are confcolor,confshape and size, which should be dropdown and with global scope, assigned to your product's attribute set.
    The script is using the csv file with three columns like this.
    <!-------------------------------->
    ConfSku, ConfName, SimpleSku
    confsku1, confname1, simple-sku1
    confsku1, confname2, simple-sku1
    confsku1, confname3, simple-sku1
    confsku1, confname4, simple-sku1
    <!-------------------------------->
    <!------------Script Created By Shailesh Thapa ----------st.homespice@gmail.com---------->
    
    <?php 
    
        error_reporting(E_ALL); 
        ini_set('memory_limit', -1);
        ini_set('max_execution_time', -1); 
        define('MAGENTO', realpath(dirname(__FILE__)));
    	require_once MAGENTO . '/app/Mage.php';
    	Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); 
    
       $row = 0;
       $quantity =1; 
    
       if(($handle = fopen("braided-configurable-Homespice.csv", "r")) !== FALSE)
       { 
    
         $customeArray = array();
    	 $finalCustomArray = array();
    	 $i=0; 
         while(($value = fgetcsv($handle, 2000, ",")) !== FALSE) 
    	  {
    
           if($i>0 && $i< 18000) //4000000
           {   
    
    			   $customeArray[] =  $value;
    
    			   if(sizeof($customeArray)>1)
    			   {
    							  $currentRowIndex =  $i-1;
    							  $previoudRowIndex = $currentRowIndex - 1; 
    
    							  if($customeArray[$currentRowIndex][0] == $customeArray[$previoudRowIndex][0])
    							  { 
    
    								   $finalCustomArray[] = $customeArray[$previoudRowIndex];  // sku of product created earlier
    							  }
    							  else
    							  {   
    								   $finalCustomArray[] = $customeArray[$previoudRowIndex];  //  sku of product created earlier
    
    									 createConfigurableProduct($finalCustomArray);
    
    								   unset($finalCustomArray);
    
    							 }
    			    }
    
              }
    
    		  $i++;
    
           } 
           echo "Imported All Products";
    	   fclose($handle);
        } 
    
    		function createConfigurableProduct($associatedRecords)
    		{
    			$sku   =  $associatedRecords[0][0];
                $isExistConfigurableProduct = checkAvailability($sku);
    
    			$storeId=1;
    			$websiteIds=1;
    			$attributesetId = 10;
    			$sku =$associatedRecords[0][0]; 
    			$name = $associatedRecords[0][2]; ;
    			$price = 100;
    			$categoryIds ="239";
    			$status = 1;
    			$taxClassId = 0;
    			$visibility = 4;
    
    			$description="This is description product";
    			$shortDescription="This is short description";
    
    			$configCodeString="confcolor,confshape,size";
    			$configAttributeArray = explode(",",$configCodeString);
    
    			$associatedSkuArray = array();
    			foreach($associatedRecords as $tmpArray)
    			{
    				$associatedSkuArray[] = $tmpArray[1]; //simple products sku
    
    			}
    
    			 if( $isExistConfigurableProduct==0)
    			 {
    
    						$configProduct = Mage::getModel('catalog/product');
    						$configProduct
    							 ->setStoreId($storeId) 
    							 ->setWebsiteIds(array($websiteIds))
    							 ->setAttributeSetId($attributesetId)
    							 ->setTypeId('configurable') 
    							 ->setCreatedAt(strtotime('now')) 
    							 ->setSku($sku)
    							 ->setName($name)
    							 ->setStatus($status) 
    							 ->setTaxClassId($taxClassId) 
    							 ->setVisibility($visibility)
    							 ->setPrice($price)
    							 ->setDescription($description)
    							 ->setShortDescription($shortDescription)
    							 ->setCategoryIds(array($categoryIds))
    							 ->setStockData(array(
    												 'use_config_manage_stock' => 0, 
    												 'manage_stock' => 1, 
    												 'is_in_stock' => 1, 
    										)     );
    
    						$configurableProductsData = array();
    						$configAttributesIdsArray = array();
    						foreach($configAttributeArray as $configAttributeCode)
    						{
    						   $attributeid = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', $configAttributeCode);	
    						   $configAttributesIdsArray[] = $attributeid;
    						}
    
    						$configProduct->getTypeInstance()->setUsedProductAttributeIds($configAttributesIdsArray); 
    
    						foreach($associatedSkuArray as $simpleSku)
    						{  
    
    								$simpleProduct  =  Mage::getModel("catalog/product")->loadByAttribute("sku",$simpleSku);
    								if(is_object($simpleProduct))
    								 {
    										 $confCount =0;
    										 $simpleProductsData  = array();
    										 foreach($configAttributeArray as $configAttributeCode)
    										 { 
    											 $configAttributeid = Mage::getResourceModel('eav/entity_attribute')
    																  ->getIdByCode('catalog_product', $configAttributeCode);
    												  $value_index='';
    												  if($configAttributeCode=='confcolor')
    												  { $value_index = $simpleProduct->getConfcolor(); }
    												  else  if($configAttributeCode=='confshape')
    												  { $value_index = $simpleProduct->getConfshape(); }
    												  else  if($configAttributeCode=='size')
    												  { $value_index = $simpleProduct->getSize(); }
    
    											 $simpleProductsData[$confCount] =    array(
    																						  'label'         => $simpleProduct->getAttributeText($configAttributeCode),
    																						  'attribute_id'  => $configAttributeid,
    																						  'value_index'   => $value_index,
    																						  'is_percent'    => 0,
    																						  'pricing_value' => $simpleProduct->getPrice(),
    
    																					   );
    
    											 $confCount++;
    										 }
    										 $configurableProductsData[$simpleProduct->getId()] = $simpleProductsData;
    								 }
    						 }
    
    						 $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
    
    						 $configProduct->setConfigurableProductsData($configurableProductsData);
    						 $configProduct->setConfigurableAttributesData($configurableAttributesData);
    						 $configProduct->setCanSaveConfigurableAttributes(true);
    
    						 $configProduct->save(); 
    						 echo "Configurable Product with SKU = $sku created<hr><br>"; //die;
    
    			 }
    			 else
    			 {
    			        echo "Configurable Product with SKU = $sku already exist<hr><br>"; 
    
    			 }
    
    		}
    
    	function checkAvailability($productSku)
    	{
    
    	   $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $productSku);  
    
    	   if(is_object($_product))
    	   {
    
    			   $sku = $_product->getSku();
    			if($sku!='')  
    			{
    			   return 1;	
    			}
    			else
    			{
    			 return 0;
    			} 
    
    	  }
    	  else
    	  {
    			return 0;
    	  }
    	}
    
    ?> 
  3. I always get “Fatal error: Call to a member function getTypeInstance() on a non-object” on the line where i
    use: $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();” with your code. When I debug the code, $configurableAttributesData doesn’t return the attributes had been assigned to be configurable. Please help! Thanks.

  4. The configurable product is created, I can see it in the product grid, but when trying to edit it, it would ask me what configurable attributes to used, the same as the fist step when creating a configurable product from the product management.

  5. Hi. this code is work well..but when page load it automatically create a product. what i need is when i click add button after that create a product. i wrote onclick function in button field but its not work. how it fixed

  6. hello,
    i try this code, its work very nice, but pricing_value not working.
    please help.

  7. Hi i am getting error

    Fatal error: Uncaught exception ‘Mage_Core_Exception’ with message ‘The product could not be found.’ in /public_html/clients/preptable/app/Mage.php:595 Stack trace: #0 /public_html/clients/preptable/app/code/core/Mage/Checkout/Model/Cart.php(211): Mage::throwException(‘The product cou…’) #1 /public_html/clients/preptable/app/code/core/Mage/Checkout/Model/Cart.php(248): Mage_Checkout_Model_Cart->_getProduct(Object(Mage_Catalog_Model_Product)) #2 /public_html/clients/preptable/product1.php(40): Mage_Checkout_Model_Cart->addProduct(Object(Mage_Catalog_Model_Product), Object(Varien_Object)) #3 {main} thrown in /public_html/clients/preptable/app/Mage.php on line 595

    I have added a product by code in magento 1.9 then i am trying to add same product into cart, it shows this error, but if i go into admin and then save that product again then add same product into cart by code, it works, so the problem is when i add product in magento by code and then in next line i add it in cart using below code it shows this error.

    $session = Mage::getSingleton(‘customer/session’);
    $cart = Mage::getSingleton(‘checkout/cart’);

    $cart->init();
    //Mage::getSingleton(‘checkout/cart’)->truncate();
    $productInstance = Mage::getModel(‘catalog/product’)->load($productId);
    $params = array(
    ‘product’ => $productInstance->getId(),
    ‘qty’ => 1,
    ‘options’ => $optionvalue
    );

    $request = new Varien_Object();
    $request->setData($params);
    $cart->addProduct($productInstance, $request);
    $session->setCartWasUpdated(true);
    $cart->save();

    Any help would be really apprecitaed i have tried a lot of codes but none of them seems to be working.

  8. i want show default price in configureable product
    there are 4 simple product in 1 configureable product
    please help me out how to show default price

    1. first, there must be 4 associated product (4 simple product) with 1 configurable product in your case, that 4 associated product will must contain your default product if not add it via create and then price it. Your default product price will be shown to your store.

  9. hi. this one is very helpful. i will derive from your code and create a simple library to easily create configurable product. will share this here as soon as i’m done. thank you very much for posting this. pretty weird that the standard Magento APi didn’t support this up till now. (using CE and the madison island to check stuff).

  10. i want show default price in configureable product
    there are 4 simple product in 1 configureable product
    please me help out how to show default price

  11. i always get “Fatal error: Call to a member function getTypeInstance() on a non-object” on the line where i
    use: $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();

    1. I always get “Fatal error: Call to a member function getTypeInstance() on a non-object” on the line where i
      use: $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();” with your code. When I debug the code, $configurableAttributesData doesn’t return the attributes had been assigned to be configurable. Please help! Thanks.

  12. Awesome thnx, but for me its working without this line of code,dont know why

    $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();

  13. I was wondering about displaying simple product price when setting up a configurable product? Magento allows you to add or subtract but that might get confusing.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.