Search code examples
eventsmagentoobservers

Implementing an event observer in Magento


Im starting to understand how Magento Event Observers work and hoping someone could help me figure out what Event I would need to seek out to get my potential module to work. I have certain products that have an attribute called "child skus" which is an array of SKU numbers of other products in my inventory.

Example:

Name: Totally Awesome Product

SKU: TP-1212

Child SKUS: GP-3232,FD-4332,VC-5332

Every time someone purchases TP-1212 I also need Magento to deduct that quantity from those child skus behind the scenes. Does anyone know if there is an event dispatcher for after a purchase has been completed that would handle something like that??


Solution

  • This is a little tricky and there are most likely some edge cases not covered in the below code - Also the answer assumes the following:

    1. You wish to reduce the stock level of all associated products of the parent just purchased
    2. You wish to reduce by only 1
    3. There are no further complications or other conditions that must be met/dealt with

    Code:

    So, you obviously need to create a module first. The config.xml needs to declare the observer which will listen to checkout_type_onepage_save_order_after. (Note: there are other events you can listen to in order to achieve your goal).

    The config.xml will contain the following code at a minimum:

    <?xml version="1.0"?>
    <config>
        <modules>
            <YourCmpany_YourModule>
                <version>1.0.0</version>
            </YourCmpany_YourModule>
        </modules>
        <frontend>
            <events>
                <checkout_type_onepage_save_order_after>
                    <observers>
                        <yourmodule_save_order_observer>
                            <class>YourCompany_YourModule_Model_Observer</class>
                            <method>checkout_type_onepage_save_order_after</method>
                        </yourmodule_save_order_observer>
                    </observers>
                </checkout_type_onepage_save_order_after>
            </events>
        </frontend>
        <global>
            <models>
                <yourmodule>
                    <class>YourCompany_YourModule_Model</class>
                </yourmodule>
            </models>
        </global>
    </config>
    

    Then in your observer:

    <?php
    
    class YourCompany_YourModule_Model_Observer
    {
        public function checkout_type_onepage_save_order_after(Varien_Event_Observer $observer)
        {
            $order = $observer->getEvent()->getOrder();
    
            /**
             * Grab all product ids from the order
             */
                $productIds = array();
            foreach ($order->getItemsCollection() as $item) {
                $productIds[] = $item->getProductId();
            }
    
            foreach ($productIds as $productId) {
    
                $product = Mage::getModel('catalog/product')
                    ->setStoreId(Mage::app()->getStore()->getId())
                    ->load($productId);
    
                if (! $product->isConfigurable()) {
                    continue;
                }
    
                /**
                 * Grab all of the associated simple products
                 */
                $childProducts = Mage::getModel('catalog/product_type_configurable')
                            ->getUsedProducts(null, $product);
    
                foreach($childProducts as $childProduct) {
    
                    /**
                     * in_array check below, makes sure to exclude the simple product actually 
                     * being sold as we dont want its stock level decreased twice :)
                     */
                    if (! in_array($childProduct->getId(), $productIds)) {
    
                        /**
                         * Finally, load up the stock item and decrease its qty by 1
                         */
                        $stockItem = Mage::getModel('cataloginventory/stock_item')
                                        ->loadByProduct($childProduct)
                                        ->subtractQty(1)
                                        ->save()
                                    ;
                    }
                }
            }
        }
    }