How to Create a Simple and Configurable Products in Magento 2 Programmatically: Technical Guide

Table of Content

Creating Magento simple and configurable products programmatically

Products are the cornerstone of any catalog or e-commerce store, and Magento offers robust features for creating them from the backend. Whether you’re looking to create simple products, grouped products with configurable products, or configure products programmatically, Magento 2 makes it possible to tailor your store's inventory.

This guide will walk you through the process of creating Magento 2 configurable products manually or programmaticallywith helpful code snippets from Amasty's expert Magento developers.

Key topics we cover below:

  • How to create a simple products programmatically in Magento 2
  • How create configurable product from existing simple products

What is a Magento 2 Product?

A Magento 2 product refers to any item available for sale on your Magento store, whether it's a physical product, a downloadable file, or a virtual item. Magento offers a range of product types, including both simple products and configurable products, to help merchants create a personalized shopping experience for their customers:

  • Magento Simple Product. A single, standalone product without any variations. It’s the most basic product type in Magento.
  • Magento Grouped Product. A collection of simple products that are sold together. Customers can select and purchase individual items from the group.
  • Magento Configurable Product. A product that allows customers to choose options like size, color, or style. It’s usually a parent product associated with one or more simple products, allowing for greater customization.
  • Bundle Product. Allows customers to choose from a set of predefined options, such as selecting different components for a kit or a custom product package.
  • Virtual Product. A non-tangible product that doesn’t require shipping, such as services or subscriptions.
  • Downloadable Product. Products that can be downloaded after purchase, like digital files, music, or software. 

Each of these product types serves a unique purpose to enhance the flexibility of your Magento store.

Why Create Products Programmatically?

Creating products programmatically in Magento 2 offers a powerful and flexible way to manage your store's inventory, automate repetitive tasks, and integrate product creation with custom workflows. There are various scenarios where you might need to create products programmatically, including:

  • Bulk Import. If you have a large number of products to add to your store, programmatically creating them allows you to import data in bulk from external sources, such as CSV files or third-party databases.

  • Batch Creation for Testing. Developers often need to quickly generate products for testing purposes, such as simulating different product variations or testing product-related features like promotions, pricing, or attributes.

  • Custom Product Creation Interfaces. If you’re developing a custom Magento interface for your customers or administrators to create products in a unique way (such as from a mobile app or through an external system), creating products programmatically can help achieve that functionality.

  • Dynamic Product Generation. You may need to create products based on specific business logic or data inputs that change frequently. This can include generating seasonal products, limited-time offers, or products with unique configurations, such as personalized or custom items.

How to Create Magento Products Programmatically (Manually)

To create a product in your Magento store’s database, you have several options:

  1. Use the API – This method is ideal for integrating various systems. We'll dive deeper into the API in a future article. However, it’s not the best approach when working within a single system.
  2. Perform a Raw Database Request – This method may seem like the quickest way to create a product, but it can lead to complications, especially when you're dealing with Magento’s EAV (Entity-Attribute-Value) storage model.
  3. Create a Mage_Catalog_Model_Product Object – The recommended approach is to create an object of the Mage_Catalog_Model_Product type, initialize it, and then save it using the appropriate method.

While raw database queries (like INSERT INTO product_tablename ...) may appear to be the easiest option, they fail to account for the complexities of Magento’s EAV architecture. If you're not familiar with this model, it could lead to problems down the road.

We’ll cover the details of EAV in upcoming articles. For now, it's important to note that creating a simple product involves updating more than 15 tables simultaneously. Below are the main tables involved in this process (click to enlarge):

The table may be a bit outdated, but it still serves our purpose: understanding the process of creating a simple product. As you can see, the values are stored across multiple tables, depending on their type. For example, dropdown attributes like color and manufacturer have separate tables for their options. Similarly, price and images are stored in distinct locations.

Here’s the good news: Magento provides the Mage_Catalog_Model_Product class, which manages data integrity and ensures correct data storage. In the following sections, I’ll show you how to use this class to streamline the process and avoid the complexities of manually handling the database.

Creating Magento 2 Simple Product: Step by Step

Step 1: Set Up the Product in the System

Start by initializing the product object and setting key attributes such as SKU, category, and visibility.

[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) 
->setSku('example_sku' . $rand) 
->setWebsiteIDs(array(1))
;
[/php]

Explanation:

  • Set Current Store: Sets the store context for the product creation.
  • Product Model: Initializes a new product model.
  • SKU & Attributes: Randomly generate an SKU and assign it to the correct attribute set (e.g., default attribute set).

Step 2: Make the Product Visible in the Catalog

Next, define product visibility and status, which determines whether the product appears on the frontend.

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

Step 3: Configure Stock Data

Set up stock data to ensure that the product is available for sale and has a defined quantity.

[php]$product->setStockData(array(
'use_config_manage_stock' => 0, 
'manage_stock' => 1, 
'is_in_stock' => 1,
'qty' => 5,
));
[/php]

Step 4: Set Product Attributes

Define key product attributes, such as name, price, and description.

[php]$product
->setName('Test Product #' . $rand) 
->setShortDescription('Description') 


->setPrice(24.50)
->setSpecialPrice(19.99)
->setTaxClassId(2) 
->setWeight(87)
;
[/php]

Step 5: Assign Dropdown Attributes (e.g., Color and Size)

If the product has configurable options, such as color or size, use their respective option IDs to assign them.

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

Step 6: Add Images to the Product

Finally, upload images to the product’s media gallery. 

[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}`
"; } } [/php]

Step 7: Save the Product

After configuring all attributes, save the product to the database.

$product->save();

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 2 create configurable product programmatically

Can we optimize this code? Absolutely! Performance should always be a priority. When creating multiple products in a loop, it's important to ensure we don't trigger unnecessary updates to the index tables after each product creation. Instead, we can delay this until the entire process is complete.
To achieve this, we can use the following code to prevent Magento from updating the index tables after every product creation:

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

By setting setIsMassupdate(true), we tell Magento that it's part of a bulk operation and should skip indexing during the process. Additionally, setExcludeUrlRewrite(true) prevents URL rewrites from being generated until all the products are created, further improving performance.

Creating Magento Simple Products
So, now we've covered how to create Magento simple products manually. However, Magento also supports more complex product types that you might need to create, such as:

  • Configurable Products
  • Grouped Products
  • Bundle Products

Each of these product types has its own unique setup and requirements. As we've promised, let's examine configurable ones. 

Magento 2 Create Configurable Product Programmatically: Step by Step

A Magento 2 configuratabe product is a parent product that has one or more associated child products. This allows customers to select from multiple options, such as size or color. The process of creating a configurable product programmatically involves several steps.

Step 1: Create Simple (Child) Products

Before creating a configurable product in Magento 2, you must first create the simple products that will be associated with it. These simple products represent different variations of the Magento configurable product.

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

Step 2: Select Magento 2 Configurable Product Attributes

Next, select the attributes that will be used for the configurable product. In Magento 2 creating attributes for configurable product will depend on your product itself. In this example, we’ll use the color attribute.

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

Step 3: Prepare Simple Product Data

Prepare the data for each simple product to associate with the configurable product. This includes attributes like price and label.

[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]

Step 4: Assign Data to the Configurable Product

Set the configurable product data and save the product.

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

Important Notes:

  • Ensure that the configurable product and its associated simple products share the same attribute set.
  • You can use more than one attribute for configuration, such as size and color.

Wrapping Up

And that’s it! You’ve now learned how to create configurable product in Magento 2 manually. For more advanced features like Magento 2 configurable product attribute options, or to integrate Magento 2 configurable product with custom options, consult the official Magento 2 documentation

Not into coding or don’t have the time to hunt down a top-rated Magento freelancer? No worries, reach out to Amasty’s Magento experts. We’ll assess your needs and deliver the perfect solution for you.

March 31, 2016
April 17, 2016
March 21, 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

Loading