Search code examples
zend-frameworkzend-viewzend-controller

Zend Framework: How to render a different action?


I have two actions that are essentially identical, but need different URLs. Normally I would use _forward() to render the other action:

class MyController extends Zend_Controller_Action
{
    public function actionOneAction()
    {
        $this->_forward('action-two');
    }

    public function actionTwoAction()
    {
        $this->view->foobar = 'foobar';
    }
}

However, I have some code the is happening in preDispatch() that I only want to execute once:

class MyController extends Zend_Controller_Action
{
    public function preDispatch()
    {
        //execute this only once before actionOne or actionTwo, but not both
    }

    public function actionOneAction()
    {
        $this->_forward('action-two'); //this won't work because preDispatch() will get called a second time
    }

    public function actionTwoAction()
    {
        $this->view->foobar = 'foobar';
    }
}

So I thought maybe I could simply call the function directly, like this:

class MyController extends Zend_Controller_Action
{
    public function preDispatch()
    {
        //execute this only once before actionOne or actionTwo, but not both
    }

    public function actionOneAction()
    {
        $this->actionTwoAction(); //execute the same code as actionTwoAction()
    }

    public function actionTwoAction()
    {
        $this->view->foobar = 'foobar';
    }
}

But now Zend Framework is complaining about not being able to find the action-one.phtml view script. I don't want to render actionOne's view script. I want to render actionTwo's view script. What do I need to do?


Solution

  • Using render() seems to do the trick:

    public function actionOneAction()
    {
        $this->actionTwoAction(); //execute the same code as actionTwoAction()
        $this->render('action-two'); //renders the same view as actionTwoAction()
    }