Redirection in Magento’s controller is simple. You just need to call a
_redirect() or
_forward() function and provide appropriate router/controller/action parameter. But if you want to redirect to some other page from Model or from Observer, then this can be tricky. Lets take an example, for explaining what I am referring to, Suppose you are building a module that will only allow user of certain group to view a product in frontend. Then, you will have options like:
Rewrite you catalog/product/view controller and add that logic.
Rewrite Block of that page and show error message accordingly.
Any other..?
Yeha, I do have another option as well. The Event-Observer Method. You can observe an event
controller_action_predispatch_catalog_product_view and set up an observer where you can write your own logic there and redirect accordingly.
You can observe that event by setting up your config something like this.
[source language=”xml”]
<controller_action_predispatch_catalog_product_view>
<observers>
<mymodel>
<type>singleton</type>
<class>mymodel/controller_observer</class>
<method>controller_action_predispatch_catalog_product_view</method>
</mymodel>
</observers>
</controller_action_predispatch_catalog_product_view>
[/source]
And on the observer’s
controller_action_predispatch_catalog_product_view method, you can check your logic for visibiliy of that product to the logged in user group and redirect if not visible.
Here’s the main point of this post (Did I take a lot of your time ?), in that same method you can directly redirect using the following snippet of code.
[source language=”php”]
Mage::app()->getResponse()->setRedirect(Mage::getUrl("myrouter/mycontroller/noview"));
[/source]
Adding an error message to the session would be a good idea, for user to understand what is happening. Else you can directly call a template in the redirected controller’s action with appropriate message.
I think this sums up the post for now..and as always hoping it helps somebody and waiting for the response.