0

I would like to be able to show in the product grid how long the item has been out of stock, is this possible?

I am presuming its only possible if there's a record of when the stock status was changed, which doesn't exist yet, but this sort of information can be recorded using an observer can't it?

What code can I use to achieve this?

  • Did you manage to get your issue resolved? – Sander Mangel Apr 16 '15 at 7:36
1

You're correct in the information not being available out of the box. Magento just records the absolute stock qty, not the stock movement.

There are as far as I can see 2 options.

Option 1: Writing your own stock movement module

You could write a module that adds a table for this data, with fields like product_id, date_updated, qty.

Then using an observer on the Mage_Cataloginventory_Model_Stock_Item model save after event (cataloginventory_stock_item_save_after) storing this data. The observer would probably look something like below

class [Namespace]_[Module]_Model_Observer
{
   public function trackStockMovement($observer)
   {
      $obj = $observer->getEvent()->getDataObject();
      $productId = $obj->getProduct()->getId();
      $qty = $obj->getQty();

      /**
       * here goes the code to save data
       */
   }
}

This would store all stock movement. Optionally you could save just when qty equals 0.

Next to that I would advice writing a cronjob in the module that cleans out stock movement older than X months to prevent massive database tables.

From that data you can retrieve the out of stock length for the frontend.

Option 2: dude... too much data

Or use a custom module that has an observer on product save (catalog_product_save_before) that stores the current date in a product attribute when stock qty equals 0. Something along this line:

class [Namespace]_[Module]_Model_Observer
{
   public function trackStockMovement($observer)
   {
      $obj = $observer->getEvent()->getDataObject();
      $qty = Mage::getModel('cataloginventory/stock_item')
           ->loadByProduct($obj->getProduct());

      if ($qty == 0 && $obj->getData('out_of_stock_since') == null) {
         $obj->setData('out_of_stock_since', time());
      } else if ($qty>0) {
         $obj->setData('out_of_stock_since', null);
      }
   }
}

Make sure you create a product attribute out_of_stock_since add set it to be used in product listing. Then add it to your category list, product view or where ever you want to display it

Disclaimer: Untested code so please do not use on live environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.