Magento – Code before a controller’s action is executed

admincontrollersmagento-1.7PHP

I would like to write some custom code before any actions in a controller is executed. It would seem like an easy one, but i am unable to find help anywhere in google. I tried to override preDispatch() function in my controller, but it ends up getting weird (instead of showing my page, it shows the default page without any content in it)

Its a admin controller and i need to do some custom validation before any action in it is executed. Based on the validation, the request may be forwarded to some other controller.

Best Answer

Good news: there's no need to rewrite preDispatch! There is dynamic eventing that is fired both before and after the dispatch:

An excerpt of what is required to tap into the event in your module's etc/config.xml file:

<global>
    <events>
        <controller_action_predispatch_catalog_product_view>
            <observers>
                <yourmodule_capcpv>
                    <class>YourCompany_YourModule_Model_Observer</class>
                    <method>catalogProductViewPredispatch</method>
                </yourmodule_capcpv>
            </observers>
        </controller_action_predispatch_catalog_product_view>
    </events>
</global>

And your observer would look like the following:

app/code/local/YourCompany/YourModule/Model/Observer.php:

<?php

class YourCompany_YourModule_Model_Observer
{
    public function catalogProductViewPredispatch($observer)
    {
        //get the controller action method
        $controller = $observer->getEvent()->getControllerAction();

        //log something
        Mage::log('Testing - I made it to the predispatch of the catalog product viewAction!');

        //get things from the request:
        $request = $controller->getRequest();

        //set things on the response:
        $reponse = $controller->getResponse();
        $response->setBody('some stuff');
    }
}
Related Topic