When a product is viewed I need to go to an external system (using a web service), query the actual stock values and update them in magento before displaying the page. This is for a configurable product so I need to handle all the associated simple products.
I've implemented an event observer capturing the catalog_controller_product_init_before event and the Observer.php module has
public function loadBeforeProductObserve(Varien_Event_Observer $observer) {
$event = $observer->getEvent();
$x = $event['controller_action'];
$id = $x->getRequest()->getParam('id');
$product = Mage::getModel('catalog/product')->load($id);
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$product);
foreach($childProducts as $child) {
$stock = $child->getData("stock_item");
if ($stock->getData("qty") == 0) {
$stock->addData(array("qty"=>27, 'is_in_stock' => 1));
//$stock->save();
}
}
}
Clearly this is running just to test the process in that it simply identifies any products with 0 stock and sets them to have 27 items.
My actual code is littered with print statements so I can see that it's finding all the right things and displaying the new values after the addData command (I've also tried setData) shows the values to be there.
When I try activating the save() function, the system fails and I get a 404 error for the page.
Without doing the save the product display is showing details as though the zero stock items are still zero and, indeed, capturing the catalog_controller_product_init_after event shows the value to be unchanged.
So what am I doing wrong? What things could I be doing better? How do I save the new stock value so that it will be used for the product display?