Creating Magento simple & configurable products programmatically

Creating Magento simple and configurable products programmatically
Posted in: Magento 2 Guides

Basically, products are the cornerstone of any catalog and e-commerce shop. And Magento has great features for creating them from backend, but there are cases when we need to when in Magento we need to programmatically create a product, or manually. For example, you may need it if you import products in a certain text format, or if you need to create plenty of products to test a shop’s performance, or you are suggesting an alternative product creation interface. So read this article if you want to add the Magento 2 product programmatically or get selected configurable product options in Magento 2.

How to create Magento simple products programmatically (manually)

To create a product in a shop’s database, we can:

  1. Make use of API (read more about it here)
  2. Perform a raw database request
  3. Create an object of Mage_Catalog_Model_Product type, initialize it and call the saving method.

We’ll talk about API in one of our upcoming articles later, it’s great for cases when integration of various systems takes place, but it’s not wise to use it within the scope of one system.
A query like INSERT INTO product_tablename ... seems to be the easiest way of creating a Magento product at first sight, but only if you’re not familiar with EAV (entity attribute value) Magento storage architecture.

We’ll tell you more about EAV in the upcoming articles, and now I just want to point out that we’ll need to update more than 15 tables simultaneously to create a simple product. Here are the main ones (click to enlarge):

 

Magento database

 

To the full version of Magento database system, click to open the PDF. The table is a bit outdated, but it'll do for our purpose here - we need to understand the process of creating a simple product.

We can see that the values are stored in several tables depending on their type. Moreover, dropdown attributes, such as color and manufacturer, have an additional table for options. Price and pictures are also stored separately.

Some good news: there is a Mage_Catalog_Model_Product class that takes care of integrity and correct data storage, and I am going to show you how to use it.
First things first, we are going to set some mandatory attributes:

[php]Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); //
$product = Mage::getModel('catalog/product');
$rand = rand(1, 9999);
$product
->setTypeId($type)
->setAttributeSetId(4) // default attribute set
->setSku('example_sku' . $rand) // generate a random SKU
->setWebsiteIDs(array(1))
;
[/php]

Now, time to make the product visible in the catalog:

[php]
$product
->setCategoryIds(array(2,3))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) // visible in catalog and search
;
[/php]

Configuring stock:

[php]$product->setStockData(array(
'use_config_manage_stock' => 0, // use global config?
'manage_stock' => 1, // should we manage stock or not?
'is_in_stock' => 1,
'qty' => 5,
));
[/php]

Specifying mandatory attributes, such as name and price:

[php]$product
->setName('Test Product #' . $rand) // add string attribute
->setShortDescription('Description') // add text attribute

// set up prices
->setPrice(24.50)
->setSpecialPrice(19.99)
->setTaxClassId(2) // Taxable Goods by default
->setWeight(87)
;
[/php]

Specifying dropdown-type attributes, such as color, size, brand:

[php]
$optionId = $this->_getOptionIDByCode('color', 'Black');
$product->setColor($optionId);
$optionId = $this->_getOptionIDByCode('size', 'M');
$product->setSize($optionId);
[/php]

All the magic happens in $product->save();
Also, we can add some pictures to our newly created Magento simple product. Put files to the /media/example/amasty/ folder:

[php] $images = array(
'thumbnail' => 'image.jpg',
'small_image' => 'image.jpg',
'image' => 'image.jpg',
);

$dir = Mage::getBaseDir('media') . DS . 'example/amasty/';

foreach ($images as $imageType => $imageFileName) {
$path = $dir . $imageFileName;
if (file_exists($path)) {
try {
$product->addImageToMediaGallery($path, $imageType, false);
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Can not find image by path: `{$path}`<br/>";
}
}
[/php]

Done! We have a simple product created. If you still can’t see it on the frontend, reindex and clear your cache. We always tell you to do this because it’s rather an important step than a simple recommendation.

 

Magento simple product created programmatically (manually)

 

Can we make this code better? Of course we can; never forget about performance optimization. If we create several products in a cycle, we need to tell the Magento core that the index tables needn’t be updated after each product creation; it’s better to do it at the end of the whole task.

[php] $product->setIsMassupdate(true)->setExcludeUrlRewrite(true);[/php]

So, we learned how to create Magento simple products manually. But, as we know, Magento has complex product types, such as:

  • Configurable
  • Grouped
  • Bundle ones.

How to create Magento 2 configurable products programmatically (manually)

Now, we’ll step forward to create a configurable product. Say, we’ll make just one configuration options – color. In any way, we need at least two products: one parent configurable product and one child simple product.

[php]
$simpleProduct = $this->_createProduct(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE); // create simple
product
$confProduct = $this->_createProduct(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE, false); // cre
ate conf product but do not save
[/php]

Then associate simple (child) product with the configurable (parent) product. There are several options of doing it, but not all of them work well with recent CE 1.9+ Magento versions. We will show you the easiest one. Just follow these 4 steps:

1. Select configurable attributes:

[php]
$colorAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');
$confProduct->getTypeInstance()->setUsedProductAttributeIds(array($colorAttributeId));
[/php]

2. Prepare information for each of the simple products:

[php]
$configurableProductsData = array();
$configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray();

$simpleProductsData = array(
'label' => $simpleProduct->getAttributeText('color'),
'attribute_id' => $colorAttributeId,
'value_index' => (int) $simpleProduct->getColor(),
'is_percent' => 0,
'pricing_value' => $simpleProduct->getPrice(),
);

$configurableProductsData[$simpleProduct->getId()] = $simpleProductsData;
$configurableAttributesData[0]['values'][] = $simpleProductsData;
[/php]

3. Set data in 2 required formats:

[php]
$confProduct->setConfigurableProductsData($configurableProductsData);
$confProduct->setConfigurableAttributesData($configurableAttributesData);
[/php]

4. Save product with a special flag:

[php]
$confProduct->setCanSaveConfigurableAttributes(true);
$confProduct->save();
[/php]

N.B. We need to have the same attribute set in the configurable product and its associated product both.
Voila, we created a configurable Magento product manually. But today I have something more in the pocket.

March 31, 2016
April 17, 2016
March 25, 2016
Comments
Bruno
April 22, 2015
Hi. I´ve downloaded the module and an error ocurred to me. " Fatal error: Call to a member function getId() on a non-object in C:\wamp\www\magento\app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php on line 276 " . The error is caused by: $configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray(); I´m using Magento CE 1.9 Can you help me??
Reply
Ksenia Dobreva
April 22, 2015
Hey Bruno, sorry that you have experienced an error here. Please note that the attribute which you configure your product by (color, brand) should be: 1) Type = dropdown 2) Use To Create Configurable Product = Yes 3) The attribute should be added to the standard attribute set, see admin > catalog > attributes > manage attribute sets. For example, you can set these settings for color attribute at: admin > catalog > attributes > manage attributes > color Hope that helps. Please let me know if the settings work for you.
john
February 2, 2018
Hi. I´ve downloaded the module and an error ocurred to me. ” Fatal error: Call to a member function getId() on a non-object in C:\wamp\www\magento\app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php on line 276 ” . The error is caused by: $configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray(); I´m using Magento CE 1.9 Can you help me??
john
February 2, 2018
not working :(
Pawel
June 7, 2015
I woukd like to download this deme but I can't subscribe. I didn't get confirm email. Can you help me?
Reply
Pawel
June 7, 2015
sorry, i just get email.
Ksenia Dobreva
June 8, 2015
Hey there, yes, sometimes it takes time for the confirmation email to get into your inbox. Glad you finally received it. Cheers!
wachdia
June 10, 2015
Hello please told me what is $this in "1 2 3 4 $optionId = $this->_getOptionIDByCode('color', 'Black'); $product->setColor($optionId); $optionId = $this->_getOptionIDByCode('size', 'M'); $product->setSize($optionId); " Many thanks!
Reply
wachdia
June 10, 2015
O oh, I'v got it, ye ye, thanks for good article :D
Ksenia Dobreva
June 10, 2015
Glad you sorted it out, thanks for commenting!
SasiKiran
July 12, 2015
Hi. I have followed the steps mentioned in this article. I have created an simple product, it is showing in the admin panel->manage products. But it is not showing in frontend, and when i again save from admin panel. its showing in frontend. Please help me on this. Thanks Sasikiran
Reply
Ksenia Dobreva
July 12, 2015
Hello and thanks for the question. Do you clear cache after creating the product?
SasiKiran
July 13, 2015
Works Like Charm. Thank you Ksenia
David
August 6, 2015
Thanks a lot! Your comment hint "create conf product but do not save" was my day saver! I tried for hours to add some simple products to the configurable, with a lot of different code, but it never worked. So i changed it, that the configurable product is not saved before the simple products are linked to it. Now it works in Magento 1.9.1! :-)
Reply
Ksenia Dobreva
August 6, 2015
Thanks for commenting, David! Glad you found a solution here.
jack
August 12, 2015
Hi, how can we set the attribute price in configurable product? your code works fine. but i don't know how to set the price in attribute values. any help would be greatly appreciated.
Reply
Ksenia Dobreva
August 13, 2015
Hey Jack, thanks for asking. Basically, you can set price the same way as in the child products: $confProduct->setPrice(24.50) Hope that helps.
Rahul
January 12, 2016
Hi, I want to upload bilk amount of products in my magento store (around 2 -3 lakhs). I am newbie in magento can you please help to how is this possible. how to run your script and where.
Reply
Ksenia Dobreva
January 12, 2016
Hi Rahul, thanks for your question. If you want to import your own products, this script won't help you at all, because it creates new products for testing. In general, if you want to import such a big database of products, you should divide it in parts which your Magento memory and server can digest one by one. Or find another script which simplifies importing large catalogs. Good luck with your task!
dhananjay
April 5, 2016
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.
Reply
Ksenia Dobreva
April 5, 2016
Hey Dhananjay, thanks for asking. Try to use the following code: $product = Mage::getModel('catalog/product') ->setStoreId(Mage::app()->getStore()->getId()) ->load($productInfo); Ass it is in the method _getProduct If it does not help, just debug the class \app\code\core\Mage\Checkout\Model\Cart.php, method _getProduct with a profiler to see what is wrong with the parameters.
dhananjay
April 5, 2016
I got it fixed just wrote a code to again save the product after creating it, and it is working now. Thanks for the reply
Wasim
April 9, 2016
Hi i want to know that how header menu is working with the admin dashboard like when someone adding the product the automatically show at frontend so can anyone tell me that how its works and what is the file name to see what the coding part........ any help would be much appreciated......... thanks.
Reply
Vikas Verma
June 2, 2016
hi, How can i add different prices for different attribute options ?
Reply
Vikas Verma
June 2, 2016
ohh. got it.
Ksenia Dobreva
June 3, 2016
Glad you figured that out!
Denis
June 9, 2016
CONNECT ERROR: Package file is invalid Invalid package name, allowed: [a-zA-Z0-9_-] chars Invalid version, should be like: x.x.x Invalid stability Invalid date, should be YYYY-DD-MM Invalid channel URL Empty authors section Empty package contents section
Reply
Ksenia Dobreva
June 9, 2016
Hey Denis, you should copy the files via FTP, it's not a package and it shouldn't be installed as an extension. It's a sample script. Hope that helps!
Andrea
July 8, 2016
Hello, great article. But I receive a fatal error when updating dropdown-type attributes: PHP Fatal error: Using $this when not in object context in /var/www/magento/create-simple-product.php on line 40
Reply
Ksenia Dobreva
July 8, 2016
Hey Andrea, thanks for asking! The thing is, we don't have a create-simple-product.php file in our archive...
Andrea
July 8, 2016
Sorry, I should not have included my file name. Either way, it does not want to accept $this and says it's not in object context
Ksenia Dobreva
July 8, 2016
Hey Andrea, Please download and install the whole module. Then modify app\code\local\Amasty\Example\controllers\AmastyController.php according to your needs. I'm afraid it's not possible to get some part of the code and use without the corresponding environment successfully. Hope that helps!
Andrea
July 8, 2016
I'd like to use your script and have updated my file to include all lines of code written in this article. However, I'm still having trouble with $this when updating dropdown-type attributes. Any ideas?
Ksenia Dobreva
July 8, 2016
Hey Andrea, well, it's a shame this didn't work. Unfortunately, we just can't suggest anything here because we aren't able to see your file, its contents, how the script code was used etc from our side. Good luck, Andrea!
Andrea
July 9, 2016
No problem, I understand. I was able to figure it out after a few trials. Thanks again for the great tutorial!
Ksenia Dobreva
July 9, 2016
Glad to hear it! Thanks for reading!
Siddhartha Gupta
July 14, 2016
Hey where to put this file to make it run in magento?
Reply
Ksenia Dobreva
July 28, 2016
Hey there, everything is described in the article. If you're still experiencing difficulties here, maybe you shouldn't do it right now because the instructions require a certain level of Magento and PHP knowledge.
baby in magento
March 10, 2017
hi , Short : please help me here : https://magento.stackexchange.com/questions/163810/how-to-use-controller-code-in-template-phtml-file In detail : i am using your code in addtocart.phtml file as below , but there , after clicking link its not creating any products : <?php echo 'See <a>getId() . '">created simple product</a>' ?>
Reply
baby in magento
March 10, 2017
full code : <?php echo 'See <a>getId() . '">created simple product</a>' ?>
baby in magento
March 10, 2017
<?php echo 'See <a>getId() . '">created simple product</a>' ?>
baby in magento
March 10, 2017
i found solution : public function createSimpleProductAndRedirectAction() { if($product = $this->_createProduct(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)){ $this->_redirect(Mage::getBaseUrl()."catalog/product/view/id/".$product->getId()); } } Thnaks a lot , you guys are awesome......
Ksenia Dobreva
March 27, 2017
Hey there, sorry for the late reply. Glad that you found the solution! Thanks for sharing!
Jasin
April 4, 2017
Will it display the simple product price of the item selected in dropdown?
Reply
Felipe Marques
November 7, 2017
It doesnt work! Ok, the simple product and the configurable product are created successfully. But the simple product not is associated to the configurable product. Can you help me?
Reply
john
February 2, 2018
Hi. I´ve downloaded the module and an error ocurred to me. ” Fatal error: Call to a member function getId() on a non-object in C:\wamp\www\magento\app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php on line 276 ” . The error is caused by: $configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray(); I´m using Magento CE 1.9 Can you help me?? i followed your below steps but facing same error Please note that the attribute which you configure your product by (color, brand) should be: 1) Type = dropdown 2) Use To Create Configurable Product = Yes 3) The attribute should be added to the standard attribute set, see admin > catalog > attributes > manage attribute sets. For example, you can set these settings for color attribute at: admin > catalog > attributes > manage attributes > color Any other solution to get this error fix and add configurable products successfully ????
john
February 2, 2018
Hi. I´ve downloaded the module and an error ocurred to me. ” Fatal error: Call to a member function getId() on a non-object in C:\wamp\www\magento\app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php on line 276 ” . The error is caused by: $configurableAttributesData = $confProduct->getTypeInstance()->getConfigurableAttributesAsArray(); I´m using Magento CE 1.9 Can you help me??
Reply
john
February 8, 2018
how can we add more than one simple products with one configurable product? and how we can add new attributes like green, red etc in color attribute set ? your script is assigning value to already added attributes but not creates new one.
Reply
Alina Bragina
April 13, 2018
Hi John, thanks for commenting! Pity you had the issue. Please, try the code $configurableAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product) to solve it. On the second question, sorry, but it looks like it could be rather difficult to answer it in this post. We'll try to see if we can cover this question in the future articles. Cheers!
Ravindra
October 1, 2018
I found many informative blog but this blog is full of information and well written, and i am so excited to read this.. Thanks a lot.
Reply
Leave your comment

Your email address will not be published

This blog was created with Amasty Blog Pro

This blog was created with Amasty Blog Pro

© 2009-2022 Amasty. All Rights Reserved.