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:
- 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.
- 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.
- 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.
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.