How to create Magento simple & configurable products programmatically

How to create Magento simple & configurable products programmatically

0 39400
Create Magento products programmatically

Without products a Magento shop is useless. Of course you can create Magento products from backend, but some particular circumstances may lead to a need of creating products manually, using coding (programmatically).
Developers or store owners use this method when they need to create a large number of products fast for testing, or when they need to import products in a certain text format. Because creating 1000 of products from backend may be a pain!

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

  1. Use API
  2. Perform a raw database request
  3. Create an object of Mage_Catalog_Model_Product type, initialize it and call the saving method.

The API method is working nice for integration of various systems, but when we’re talking about one store, it’s not worth doing. A query like INSERT INTO product_tablename… is the simplest way of creating a Magento product, but only if you’re not familiar with EAV (entity attribute value) Magento storage architecture.

Now pay attention, that we need to update at least 15 db tables at the same time to create a simple product. Below you can find the main tables we need to update.

Here is the Magento database system: click!

It’s not completely up to date, but it helps us to understand how it actually works.

As seen in the scheme, the values are stored in several tables depending on their type. What is more, there is an additional table for dropdown attributes, such as color or manufacturer. Magento stores price and pictures separately as well.

When performing this task, you should know that Mage_Catalog_Model_Product class is responsible for integrity and correct data storage, and we will use it while creating simple and configurable products.

Set some mandatory attributes:

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));

Make the product visible in the catalog:

$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

Configure stock:

$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,
  ));

Specify mandatory attributes, such as name and price:

$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)
  ;

Specify dropdown attributes, such as color, size and brand:

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

And finish it with $product->save(); To add pictures to the simple product we created, put them into the according folder:

$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/>";
  }
}

We’re finished here and we have a simple product in our store. Don’t forget to reindex and clear cache to see it on the frontend.

Now, we are going to make this code even better.

A good optimization trick is to tell Magento that it shouldn’t update the index tables after each product creating when we’re doing this in a cycle. Inform Magento about it at the end of the task:

$product->setIsMassupdate(true)->setExcludeUrlRewrite(true);

Now, as we managed the simple products creating, we’re going to create a configurable Magento product as well.

For this example, we will be using only one configuration option. And we need at least two products: one parent configurable product and one child simple product.

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

You can use several options to associate simple (child) product with the configurable (parent) product, but in order it works well with the latest Magento versions, use the following one.

1. Select configurable attributes:

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

2. Set info for each of the simple products:

$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;

3. Set data in 2 required formats:

$confProduct->setConfigurableProductsData($configurableProductsData);
$confProduct->setConfigurableAttributesData($configurableAttributesData);

4. Save product with a special flag:

$confProduct->setCanSaveConfigurableAttributes(true);
$confProduct->save();

NB: There must be the same attribute set in the configurable product and its associated product both. As you see, creating simple and configurable Magento products is relatively easy. Good luck with making your Magento store better!

Author Bio: Alex is a Certified Magento Developer and Zend Certified Engineer. Hi is a co-founder of Amasty – a company developing high-quality Magento extensions.

SIMILAR ARTICLES


NO COMMENTS

Leave a Reply