I have created an event which checks that if the backorder quantity of an item is greater than zero than set the ordered product quantity to zero instead of keeping it in negative and also change its status to out of stock but nothing works.
config.xml
<sales_order_place_after>
<observers>
<some_random>
<class>My_Model_Observer</class>
<method>checkBackOrder</method>
</some_random>
</observers>
</sales_order_place_after>
Observer.php
public function checkBackOrder($observer)
{
$order = $observer->getOrder();
$customer = $order->getCustomer();
foreach ($order->getAllItems() as $item)
{
if ($item->getProductType() == 'simple') {
$product = Mage::getModel("catalog/product")->load($item->getProductId());
if ($item->getQtyBackordered() > 0) {
$webQty = $product->getStockItem()->getQty();
if ($webQty <= 0) {
$this->_changeStockStatus($product);
}
}
}
}
}
protected function _changeStockStatus($product)
{
$webStockId = Mage::app()->getWebsite()->getStockId();
$store = Mage::app()->getStore()->getStoreId();
$stockItem = Mage::getModel('cataloginventory/stock_item')->setStoreId($store)->loadByProduct($product->getId());
$stockItem->setData('qty', 0);
$stockItem->setIsInStock(false)->setStockId($webStockId)->save();
}
As you can see in the code that I am not doing something complex except trying to change the item quantity and setting it status to "Out of stock" but when I execute this code it does not change the quantity or the status of an item.
Can someone please tell me what I am doing wrong here?
Best Answer
Try the following.
And the just save the product. Also you can refer few links here,
How can i quick update of qty and stock and all inventory fields in Magento
How to set a product to be in/out of stock programatically