Zend Framework: Redirection

Just a small tips, for sometimes we will forget some simple codes. I wrote this post for my future reference, just like the rest of the codes.

To redirect in Zend Framework, ex: from from action to another, like from register page to main main page, use the helper called redirector.

You can call redirector passing an action name to redirect to that action.

public function registerAction()
{
    //is registration is successful, go to the main page
    $this->_helper->redirector('index');
}

However, please take not the index here is actually the default action for the current controller. Another example:

public function addAction()
{
    //if add was successful, go to list page
    $this->_helper->redirector('list');
}

To redirect to another controller, example, when a user attempts to view a certain page, but needs to log in first, thus we will redirect to login page.

//inside a controller
$this->_helper->redirector->gotoRoute(
    array(
        'controller' => 'login',
        'action' => 'index'
    )
);

Redirector has a method called gotoRoute which can accept an array that contains the destination controller/action. The example will redirect to the login controller, index action.

For direct url: gotoRoute method can also accept a full path of URL to where we should be redirecting.

$this->_helper->redirector->gotoUrl('/users/edit/userid/' . $userId);
This entry was posted in Zend Framework and tagged , , , , , , , , , . Bookmark the permalink.

Related Posts

One Response to Zend Framework: Redirection

  1. Marco says:

    very useful. Thank you!!

Leave a Reply

Your email address will not be published. Required fields are marked *