Set default product values when adding new product

2020-02-12 07:39发布

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);
        }

2条回答
2楼-- · 2020-02-12 08:12

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.

查看更多
我命由我不由天
3楼-- · 2020-02-12 08:17
....

//$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/

查看更多
登录 后发表回答