I am trying to update the stock quantities of products in Magento from within a script.
I load the product, set the stock quantity, and save - but the quantity remains unchanged.
// get stock data
$stockData = $product->getStockItem();
printf(PHP_EOL.'Stock: qty=%d, instock=%s, man_stock=%s, use_cfg_man_stock=%s'.PHP_EOL,
$stockData->getData('qty'),
$stockData->getData('is_in_stock'),
$stockData->getData('manage_stock'),
$stockData->getData('use_config_manage_stock')
);
// prints out qty=0, instock=, man_stock=, use_cfg_man_stock=
// $stockQty = 1
$product->stockItem->setData('qty', $stockQty);
$product->stockItem->setData('is_in_stock', $stockQty>0 ? 1 : 0);
$product->stockItem->setData('manage_stock', 1);
$product->stockItem->setData('use_config_manage_stock', 0);
$product->save();
$product->load();
$stockData = $product->getStockItem();
printf('New Stock: qty=%d, instock=%s, man_stock=%s, use_cfg_man_stock=%s'.PHP_EOL,
$stockData->getData('qty'),
$stockData->getData('is_in_stock'),
$stockData->getData('manage_stock'),
$stockData->getData('use_config_manage_stock')
);
// prints out qty=0, instock=, man_stock=, use_cfg_man_stock=
Where am I going wrong?
All you were missing is to save the
$stockItem
. You shouldn't need to create a newstock_item
nor should you have to save the product.I've solved it myself:
By creating a new StockItem, and assigning that to the product. Hope this helps someone else.
To display stock quantity for the product -
And if you want to display individual data use this -
In my case I got the same problem with products that I've imported programmatically. I just realized that I forgot to add stock_data in the array...
Without stock data information, Magento generates an exception(at \Mage_CatalogInventory_Model_Stock_Item) when adding product to cart.
With this node, it works. =)