branko ajzele, senior developer / project manager

Posts / Articles

Programatically (manually) creating simple Magento product

Here is a working sample of code for programatically (manually) creating simple Magento product from within your custom code.

<?php
 
//$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();
 
// Build the product
$product->setSku('some-sku-value-here');
$product->setAttributeSetId('some_int_value_of_some_attribute');
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setCategoryIds(array(7)); # some cat id's, my is 7
$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99); # Set some price    

# Custom created and assigned attributes
$product->setHeight('my_custom_attribute1_val');
$product->setWidth('my_custom_attribute2_val');
$product->setDepth('my_custom_attribute3_val');
$product->setType('my_custom_attribute4_val');
 
//Default Magento attribute
$product->setWeight(4.0000);
 
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
$product->setStockData(array(
    'is_in_stock' => 1,
	'qty' => 99999
));
 
$product->setCreatedAt(strtotime('now'));
 
try {
	$product->save();
}
catch (Exception $ex) {  
	//Handle the error
}
 
?>

Although the process seems pretty straight forward, keep an eye on setStockData method. I was getting some foreign key constraint errors when trying to create instance of stock item then save it into the product object. The above code should handle it quite nicely. Tested on latest Magento version, which is 1.3.2.3 as of time of this writing.

View Comments

  1. Antony /

    hai…am new to magento… where should i copy this file to work on it..

  2. Hello,

    For Quick simple product creation I have found faster way of doing it
    That is for the Associated products for Configurable products.
    Take a look.
    http://magentocoder.jigneshpatel.co.in/php/automated-quick-simple-product-creation-in-magento/

    That will surely save much time.

  3. Hi!
    When trying to use this code, I’m getting:
    Fatal error: Call to a member function getResourceModelInstance() on a non-object in /var/www/test/app/Mage.php on line 347

    Newest version(1.3.2.3) clean instalation.
    Added require_once(‘app/Mage.php’); and commened out custom attributes?
    Any ideas what I’m doing wrong.
    Thanks in advance for answer.

  4. thanks for the sample. I’m currently doing a fully automated product import with data from SAP and a MAM. This was a nice start to go deeper into creating configurable products out of a list of simple products and manage attributes etc.

    thanks for sharing!

  5. JeffC /

    Thank you very much for this article.
    It helped me greatly with my current project.

    One thing I still need to do is figure out the adding of images for each product.

    Could you possibly have any examples for entering product images along with the code you have here?

    Thanks for the knowledge.

  6. Hi,
    I have a question, the script is calling method $product->save();
    as I understand this method inserts data in database and I need to update products, what should i do?

  7. If I fed it a list of products would it be faster than using the import wizard thingy?

  8. thanks for the sample. I'm currently doing a fully automated product import with data from SAP and a MAM. This was a nice start to go deeper into creating configurable products out of a list of simple products and manage attributes etc.

    thanks for sharing!

  9. What about if I want just update a product?

  10. If you want to update an existing product, insert this line after $product = ….

    $product->load( <productid> );
    or $product->loadByAttribute( 'sku', <productSKU> );

    then the $product->save() later on will update the data instead of creating a new product.

  11. Hi,

    What about the multi-languages products?
    I'm trying to add multiples products with same SKU and different WebsiteIds but this not work !

    Thanks

  12. Hi,

    I have coninued to search for a solution and i have finded it !

    I create a product like you explaned it.
    After i reload this product and i do

    $product->setStoreId(2)->setDescription('My description');
    and after $protuct->setStoreId(2)->save();

    I don't know if it is necessary to repeat always setStoreId(2) but i think if y don't do it, it will overwrite the default value.

    Sorry for my english, i'm from belgium.

    Bye

  13. Hi,

    I have coninued to search for a solution and i have finded it !

    I create a product like you explaned it.
    After i reload this product and i do

    $product->setStoreId(2)->setDescription('My description');
    and after $protuct->setStoreId(2)->save();

    I don't know if it is necessary to repeat always setStoreId(2) but i think if y don't do it, it will overwrite the default value.

    Sorry for my english, i'm from belgium.

    Bye

  14. prajeesh /

    I had tried with ths same code you have given.Added some extra code in top ,following are the code
    require_once ( “magento/app/Mage.php” );
    umask(0);
    Mage::app(“default”);

    Then got foreign key violation error in exception handler
    SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento/catalog_product_entity`, CONSTRAINT `FK_CATALOG_PRODUCT_ENTITY_ATTRIBUTE_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DELETE CASCADE)
    [string:private] =>

  15. raiz_meno /

    I have added product dynamically in the back end but it is not getting displayed in the frontend of magento.So that I am unable to redirect to checkout page,please help meeeee.

  16. zafar_insync /

    public function products(array $importData)
    {
    try
    {
    $this->getProductTypes();
    $collection = Mage::getResourceModel('tax/class_collection')
    ->addFieldToFilter('class_type','PRODUCT')
    ->load();
    foreach($collection as $taxes)
    {
    $taxArray[$taxes->getClassName()] = $taxes->getClassId();
    }
    $store = $this->getStoreByCode($importData['store']);
    $website = Mage::app()->getWebsite(trim($importData['websites']));
    $attributeSet = $this->getProductAttributeSets();
    $product = new Mage_Catalog_Model_Product();
    $product->setStoreId($store->getId());
    $product_id = $product->getIdBySku($importData['sku']);
    if($product_id)
    {
    $product->load((int)$product_id);
    }
    $product->setTypeId('simple');
    $product->setAttributeSetId($attributeSet[$importData['attribute_set']]);
    $product->setSku($importData['sku']);
    $product->setName($importData['name']);
    $product->setCategoryIds(array($importData['category_ids']));
    $product->setWebsiteIds(array($website->getId()));
    $product->setDescription($importData['description']);
    $product->setShortDescription($importData['short_description']);
    $product->setPrice($importData['price']);
    $product->setWeight($importData['weight']);
    if($importData['status'] == 'Enabled')
    {
    $status = 1;
    }
    else
    {
    $status = 0;
    }
    $product->setStatus($status);
    $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
    $product->setStockData(array(
    'is_in_stock' => $importData['is_in_stock'],
    'qty' => $importData['qty']
    ));
    $product->setTaxClassId($taxArray[$importData['tax_class_id']]);
    $product->setCreatedAt(strtotime('now'));
    $product->save();
    return $product->getId();
    }
    catch(Exception $e)
    {
    echo $e->getMessage();
    }
    }
    I wrote the above function to add product following the above process,this function works well when I add new product but when I need to update an existing product it throws a warning “Warning: Invalid argument supplied for foreach() in /var/www/html/zafar/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 9700″.Please help me to fix this issue and suggests me how to programiticall add&update products in magento.The Magento version which I am using is magento-1.3.2.4

  17. Magenta has a strange bugfuture: update data items can only be in “admin
    store”. So if you change the items in the module, which is called from the
    frontend, then use the following scheme:

    $productId=$product->getIdBySku('123');
    $product->load($productId);
    $currentStore = $this->getStoreId();
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product->setPrice('10000');
    $product->save();

  18. The process is very slow if you've some 3k+ of record do you've any idea how to make it fast?

blog comments powered by Disqus