Rendering view script for particular controller action is really easy. Indeed, thanks to (enabled by default) ViewRenderer helper, scripts are auto-loaded: renderer searches script directory(ies) for a view script called CONTROLLER_NAME/ACTION_NAME.SCRIPT_EXTENSION once found, view is auto-rendered.

However, sometimes it’s not what you want, instead you need to render some other view depending on some internal criteria. For example, you may want to render some custom error displaying view. So, if we are positive on what we want, let me show you how to do it:

class TestController extends Zend_Controller_Action
{
    /**
     * test/index.phtml would be rendered by default
     * @return void
     */
    public function indexAction()
    {
        // render test/foo.phtml
        $this->_helper->viewRenderer('foo');

        // render bar/foo.phtml to the default response segment, without using a
        // controller view script subdirectory ("test" in this case):
        // so you may use scripts from other controllers
        $this->_helper->viewRenderer('bar/foo', null, true);

        // now render the script, as previous calls do not render anything,
        // they are just used so that default script is swapped and not rendered:
        $this->render('foo');
        // OR
        $this->render('bar/foo', null, true);
    }
}

Please, note that you do not need to provide view extension (foo but not foo.phtml or any extension you happen to use for your views) – what renderer expects is action name, and we simply swapping the current action. Internally, direct() method is called when you update view renderer, which in turn is proxy for setRender():

// allows you to set any of scriptAction, responseSegment,
// and noController in one pass.
setRender($action = null, $name = null, $noController = false)

So, you may use

$this->_helper->viewRenderer->setRender('foo');

to change current view, but this form is less common, as it requires more typing :)
NB: If you need more info on ViewRenderer there’s no better place but ZF Manual.

  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • Technorati
  • email
  • Print
  • DZone
  • eKudos
  • LinkedIn
  • StumbleUpon
  • Tumblr
  • Twitter
Trackback

no comment untill now

Add your comment now