Search code examples
phpzend-frameworkzend-framework-mvc

Redirect to a different view in the controller


This is my Zend Framework directory structure (only included what you'll need):

-Controllers
    -HomeController.php
    -IndexController.php
-Views
    -scripts
        -home
            -index.phtml
        -index
            -index.phtml

In the IndexController I want to automatically redirect them to the home view.

How do I achieve this?

This is what I have tried so far:

header('/application/views/home');

I want to redirect to a different view and controller altogether. Not a different action within the same controller.


Solution

  • you have some options:

    use the _redirect action utility method (very common)

    public function indexAction() {
        $this->_redirect('/application/views/home');
    }
    

    or use the _forward action utility method to just execute the requested action without actually redirecting

    public function indexAction() {
            $this->_forward('index', 'home');
        }
    

    you could use the action helper redirector, similar to _redirect but has many more options.

    public function indexAction() {
                $this->getHelper('Redirector')->gotoSimple('index','home');
            }
    

    This about covers the basics of redirecting inside of a controller, if you want to actually render home/index.phtml from /idex/index you could use the viewrenderer action helper.

    I'll let you unlock those secrets.