Michelangelo
Michelangelo

Reputation: 1397

Create a Magento product programmatically in the 1.7 version

why this snipped of code doesn't create a product in magento 1.7?

class MyCompany_Catalogimporter_Model_Mysql4_Importer extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {   
        $this->_init('catalogimporter/catalogimporter', 'catalogimporter_id');
    }

    public function uploadAndImport(Varien_Object $object){

        $product = Mage::getModel('catalog/product');

        $product->setSku('pro12'); 
        $product->setAttributeSetId(9);
        $product->setTypeId('simple');
        $product->setName('Product title');
        $product->setCategoryIds(array(7));
        $product->setWebsiteIDs(array(1));
        $product->setDescription('Product Full description');
        $product->setShortDescription('Product Short description');
        $product->setPrice(250.00);
        $product->setWeight(30.00);
        $product->setVisibility(4);
        $product->setStatus(1);
        $product->setTaxClassId(0);
        $product->setStockData(array(
           'is_in_stock' => 1,
            'qty' => 20
        ));
        $product->setCreatedAt(strtotime('now'));

        try { 
            $product->save(); 
        } 
        catch (Exception $e) { 
            Mage::log($e->getMessage()); //check your var/log/system.log for error
        } 

        echo "saved";
        die();  
    }

}

There are NO Errors!

UPDATE

If I create a simple file in the magento root with this following code, it works as well:

require_once('app/Mage.php');
Mage::app();

$product = Mage::getModel('catalog/product');


$product->setSku('pro111');
$product->setAttributeSetId(9);
$product->setTypeId('simple');
$product->setName('Product title');
$product->setCategoryIds(array(7));
$product->setWebsiteIDs(array(1));
$product->setDescription('Product Full description');
$product->setShortDescription('Product Short description');
$product->setPrice(250.00);
$product->setWeight(30.00);
$product->setVisibility(4);
$product->setStatus(1);
$product->setTaxClassId(0);
$product->setStockData(array(
   'is_in_stock' => 1,
    'qty' => 20
));
$product->setCreatedAt(strtotime('now'));
$product->save();

WHY?!?!?

thanks

Upvotes: 2

Views: 1392

Answers (2)

FredericoR
FredericoR

Reputation: 73

I had an issue similar to your, after a bit of headache I discovered it was a problem with duplicated SKU values.

Every time I tryed to create a product programmatically with an SKU already in my db, no erros(!) but also no new product.

Upvotes: 0

Kalpesh
Kalpesh

Reputation: 5685

Wrap your $product->save(); inside try block, that will give you the idea what is going wrong if there is any error.

try { 
    $product->save(); 
} 
catch (Exception $e) { 
    Mage::log($e->getMessage()); //check your var/log/system.log for error
} 

Paste here the errors if there are any.

Upvotes: 1

Related Questions