0

I am trying to add a product to my Magento store programmatically. Basically I'm duplicating a template and editing it:

$storeId = Mage::app()->getStore()->getId(); // get store id
$product = Mage::getModel('catalog/product')->load(186);

$new = $product->duplicate();

$new->setSku(date('YmdHis'));
$new->setData("url_path", "$name.html");

$new->setEnableGooglecheckout(0);
$new->setIsImported(0);
$new->setLinksExist(false);
$new->setDescription($desc);
$new->setMetaKeyword($desc);
$new->setCustomLayoutUpdate(NULL);
$new->setName($name);
$new->setMetaTitle($desc);
$new->setMetaDescription($desc);
$new->setLinksTitle("Visitenkarten");
$new->setWebsiteIds(array(1));
$new->setData("links_exist", "1");

$new->setStockData(array(
                   'use_config_manage_stock' => 0,
                   'manage_stock'=>1, 
                   'min_sale_qty'=>1,
                   'max_sale_qty'=>2,
                   'is_in_stock' => 1,
                   'qty' => 999
               )
);

$new->setState(1);
$new->save();

In my admin panel, the new product does show up, but the "Quantity" is empty. When I edit the product in the admin panel and save it, a "0" shows up in the Quantity field.

Can anyone help me with this?

EDIT: The question my answer has been marked a duplicate of isn't describing the same error. The code in this question is already throwing an error on execution, but my code is just creating a product only showing up on the admin panel.

0

2 Answers 2

0

You need to create a new product, duplicate the data

$product = Mage::getModel('catalog/product')->load(186);
$new = $product->duplicate();

//Set all product data

$new->setData(.........);

Create a new stock item and set the data on that object

$stockItem = Mage::getModel('cataloginventory/stock_item');

$stockItem->setData(array(
                   'use_config_manage_stock' => 0,
                   'manage_stock'=>1, 
                   'min_sale_qty'=>1,
                   'max_sale_qty'=>2,
                   'is_in_stock' => 1,
                   'qty' => 999
               )
);
$stockItem->save();

Assign new stock item to product and save.

$new->setStockItem($stockItem);
$new->getResource()->save($new);
1
  • Doesn't work for me, it throws a Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000] when executung $stockItem->save().
    – asc11
    Commented Oct 2, 2016 at 8:41
0

Inchoo has a blog article about this

<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
//    if(!$product->getIdBySku('testsku61')):

try {
    $product
//    ->setStoreId(1) //you can set data in store scope
        ->setWebsiteIds([1])//website ID the product is assigned to, as an array
        ->setAttributeSetId(9)//ID of a attribute set named 'default'
        ->setTypeId('simple')//product type
        ->setCreatedAt(strtotime('now'))//product creation time
//    ->setUpdatedAt(strtotime('now')) //product update time

        ->setSku('testsku61')//SKU
        ->setName('test product21')//product name
        ->setWeight(4.0000)
        ->setStatus(1)//product status (1 - enabled, 2 - disabled)
        ->setTaxClassId(4)//tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)//catalog and search visibility
        ->setManufacturer(28)//manufacturer id
        ->setColor(24)
        ->setNewsFromDate('06/26/2014')//product set as new from
        ->setNewsToDate('06/30/2014')//product set as new to
        ->setCountryOfManufacture('AF')//country of manufacture (2-letter country code)

        ->setPrice(11.22)//price in form 11.22
        ->setCost(22.33)//price in form 11.22
        ->setSpecialPrice(00.44)//special price in form 11.22
        ->setSpecialFromDate('06/1/2014')//special price from (MM-DD-YYYY)
        ->setSpecialToDate('06/30/2014')//special price to (MM-DD-YYYY)
        ->setMsrpEnabled(1)//enable MAP
        ->setMsrpDisplayActualPriceType(
            1
        )//display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
        ->setMsrp(99.99)//Manufacturer's Suggested Retail Price

        ->setMetaTitle('test meta title 2')
        ->setMetaKeyword('test meta keyword 2')
        ->setMetaDescription('test meta description 2')
        ->setDescription('This is a long description')
        ->setShortDescription('This is a short description')
        ->setMediaGallery(['images' => [], 'values' => []])//media gallery initialization
        ->addImageToMediaGallery(
            'media/catalog/product/1/0/10243-1.png',
            ['image', 'thumbnail', 'small_image'],
            false,
            false
        )//assigning image, thumb and small image to media gallery

        ->setStockData(
            [
                'use_config_manage_stock' => 0, //'Use config settings' checkbox
                'manage_stock'            => 1, //manage stock
                'min_sale_qty'            => 1, //Minimum Qty Allowed in Shopping Cart
                'max_sale_qty'            => 2, //Maximum Qty Allowed in Shopping Cart
                'is_in_stock'             => 1, //Stock Availability
                'qty'                     => 999 //qty
            ]
        )
        ->setCategoryIds([3, 10]); //assign product to categories
    $product->save();
//endif;
} catch (Exception $e) {
    Mage::log($e->getMessage());
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.