Magento: Adding new products programmatically
Asked Answered
R

2

10

I am trying to add products to Magento 1.5 programmatically. My script will ultimately be a cron job, regularly updating and adding products as dictated by an XML file supplied by the accounts system.

I have a problem in creating new products. The relevant code segment from my script is:

    $attributeSetId = 4;

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

    $newproduct->setTypeId('simple');
    $newproduct->setWeight($product->UnitWeight);       
    $newproduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); 
    $newproduct->setStatus(1);
    $newproduct->setSKU($SKU);
    $newproduct->setTaxClassId(0);
    $newproduct->setWebsiteIDs(array(0)); 
    $newproduct->setStoreIDs(array(1)); 
    $newproduct->setStockData(array( 
        'is_in_stock' => 1, 
        'qty' => $XMLproduct->QtyInStock,
        'manage_stock' => 1
    )); 

    $newproduct->setAttributeSetId(4);
    $newproduct->setName($product->Name);
    $newproduct->setCategoryIds(array(3)); // array of categories it will relate to

    $newproduct->setDescription($product->LongDescription);
    $newproduct->setShortDescription($product->Description);
    $newproduct->setPrice($XMLproduct->SalePrice);

    try {
        if (is_array($errors = $newproduct->validate())) {
            $strErrors = array();
            foreach($errors as $code=>$error) {
                $strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
            }
            $this->_fault('data_invalid', implode("\n", $strErrors));
        }

        $newproduct->save();
    } catch (Mage_Core_Exception $e) {
        $this->_fault('data_invalid', $e->getMessage());
    }

The product is 'half' created, but the script gives up throwing the following error:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`LittleDickyBird`.`catalog_category_product_index`, CONSTRAINT `FK_CATALOG_CATEGORY_PROD_IDX_CATEGORY_ENTITY` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity_id`) ON )' in /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#3 /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT INTO `ca...', Array)
#4 /home/default/littledic in /home/default/littledickybird.co.uk/user/htdocs/1.5/lib/Zend/Db/Statement/Pdo.php on line 234

Can anyone, please, throw any light onto what I am missing or doing wrong. As you may be able to tell from my tone, I am pretty desperate, so any help will be very much appreciated.

Thank you

Rudderpost answered 18/7, 2011 at 15:40 Comment(5)
Had a similar problem that was resolved by turning on InnoDB on MySQL. Might want to check there. Hope that helps!Collodion
Unfortunately, that doesn't seem to be the issue, as InnoDB is already active. But thank you for you help.Rudderpost
The error suggests you are trying to use a category ID that doesn't exist. Are you sure there is a category 3?Oppidan
@clockworkgeek, yep, there is a category 3 and the partially created product has been added to that category.Rudderpost
Cool, I have found the problem, the line: $newproduct->setWebsiteIDs(array(0)); should be: $newproduct->setWebsiteIDs(array(1)); Amazing how the smallest thing can waste hours!Rudderpost
M
20

AMP, the OP, already self-answered the question.

Quote:

Cool, I have found the problem, the line: $newproduct->setWebsiteIDs(array(0)); should be: $newproduct->setWebsiteIDs(array(1)); Amazing how the smallest thing can waste hours!

Note: It's absolutely OK to self-answer your own question. Please just post it as an real answer, but not in a question or comment. Posting as real answer helps to keep the "Unanswered" list more clear (avoids making other people wasting their time).

Malave answered 18/7, 2011 at 15:41 Comment(0)
D
1

Both @Jurgen and @Amp answers are perfect.

I think this could be done like this way so it becomes more dynamic

$newproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
Dilettante answered 24/6, 2014 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.