Magento 1.9 – How to Get Correct Store Context in Product Save Observer

event-observermagento-1.9magento-enterprisemultistoreproduct

I'm using the observer called catalog_product_save_after to track changes to a product. Whenever this observer fires, I don't have access to the store context. I would like to get only the store contexts that the product has been modified in.

How can I get only the stores that a product has been modified for in the catalog_product_save_after event observer?

Best Answer

A product can only be saved for one store at a time. So when saving a product, you are always in the context of a single store. The store id can be retrieved from the Varien_Event_Observer observer argument as follows:

$observer->getEvent()->getProduct()->getStoreId()

Note that saving an attribute value for a product in one store can have an impact on attribute value of the corresponding attribute for the same product in another store.

For instance, consider saving a product with id 123 for store 0(the admin store), and in which the attribute name (with attribute id 71) has been changed. When loading product id 123 again for store 1 (the default frontend store), the value of attribute name might also be updated. You can check this as follows:

  1. In the admin, go to the product edit page, and switch to store 1 using the configuration scope box. If the "Use default" checkbox is not checked, the value from store 1 is shown. Otherwise, the value from store 0 is shown.

  2. In the database, you can see this in the corresponding product attribute table, in this case catalog_product_entity_varchar. If there is no value for the combination of store id 1, entity id 123 and attribute id 71, then the value for the combination of store id 0, entity id 123 and attribute id 71 is taken.