5

I have created an Observer.php for the event catalog_product_new_action

<?php
class Starmall_Productobserver_Model_Observer
{

    public function initProduct(Varien_Event_Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
            $product->setWeight(1);
            $product->setStatus(1);
            $product->setTaxClassId(1);
            $product->setPrice(1);

            $product->setStockData(array(
                    'is_in_stock' => 1,
                    'qty' => 99999
            ));
    }

}

When I add a new product the weight, status, tax class and price are correctly set to my defaults. The stock qty and stock availability are not set.

How can I set these stock values in the observer?

NOTE: I am using in the existing Manage Product screen right after clicking the Add Product button.

The following solution works. Inventory data is set correctly (see R.S. answer) :

        public function initProduct(Varien_Event_Observer $observer)
        {
            $product = $observer->getEvent()->getProduct();
            $product->setWeight(1);
            $product->setStatus(1);
            $product->setTaxClassId(1);
            $product->setPrice(1);
            $product->setWebsiteIDs(array(1));

            $stockItem = Mage::getModel('cataloginventory/stock_item');
            $stockItem->assignProduct($product);
            $stockItem->setData('is_in_stock', 1);
            $stockItem->setData('qty', 1);

            $product->setStockItem($stockItem);
        }
A.W.
  • 2,858
  • 10
  • 57
  • 90

2 Answers2

5
....

//$product->save();

$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->assignProduct($product);
$stockItem->setData('is_in_stock', 1);
$stockItem->setData('stock_id', 1);
$stockItem->setData('store_id', 1);
$stockItem->setData('manage_stock', 0);
$stockItem->setData('use_config_manage_stock', 0);
$stockItem->setData('min_sale_qty', 0);
$stockItem->setData('use_config_min_sale_qty', 0);
$stockItem->setData('max_sale_qty', 1000);
$stockItem->setData('use_config_max_sale_qty', 0);

//$stockItem->save();

Read more at http://blog.magentoconnect.us/creating-magento-products-on-the-fly/

MagePal Extensions
  • 17,646
  • 2
  • 47
  • 62
  • Thanks! This works, slightly changed it. See edited question with solution. Problem was the `$product->save()` . This gives an exception `SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails` – A.W. Nov 09 '12 at 08:31
0

It looks like you'll need to work with the actual stock item object which is set as a property on the product object.

See Mage_CatalogInventory_Model_Observer::copyInventoryData()[link] for a reference of the stock item properties.

benmarks
  • 23,384
  • 1
  • 62
  • 84