Question

I am trying to set products stock values from an external script with this code:

$product->setStockData(array(
        'manage_stock' => 1, //'Use config settings' checkbox
        'use_config_manage_stock' => 1, //'Use config settings' checkbox
        '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
    )
);

After saving the product, whatever value I set, on the admin page I always see those values:

stock vlaues don

Other product data is saved correctly.

Magento version is 1.9.3.8.

What am I doing wrong?

Was it helpful?

Solution

Here is the working code try it:

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);

// If there's no inventory information, create a registry

if (!$stockItem->getId()) {
    $stockItem->setData('product_id', $product_id);
    $stockItem->setData('stock_id', 1);
    $stockItem->setData('manage_stock', 1);
    $stockItem->setData('qty', $qty);
} else { 
    // if there is, update it
    $stockItem->setQty($qty);
    $stockItem->setManageStock(true);
}

$stockItem->save();

OTHER TIPS

Please try the following code to set stock related data.

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
if ($stockItem->getId()) {
    $qty = 999;
    $stockItem->setQty($qty);
    $stockItem->setIsInStock(1);
    $stockItem->save();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top