Bind Zend Action with Non-Default View

Action – View

You may know that every controller’s action in Zend Framework has to be bind to a view. Normally you can disable the view for a specific action, but how about “forking” an action to render different views?!

In example when some _GET parameter is set redirect to another view? That’s rather strange and perhaps there’s a clear and yet full MVC solution! First of all you can setup all of the view variables simply in the “parent” action.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->view->title = 'This is the default action!';	
	}
}

Than the view file will contain something like:

// index/index.phtml
<h1><?php echo $this->title ?></h1>

Than whenever you have the given _GET set you can _forward to another action (perhaps with no code at all) and only a different view. Thus you don’t setup twice the view variables.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$this->view->title = 'This is the default action!';	
 
		if (isset($_GET['my_param'])) {
			$this->_forward('another');
		}
	}
 
	public function anotherAction()
	{}
}

And there are two views practically for one action:

// index/index.phtml
<h1><?php echo $this->title ?></h1>
 
// index/another.phtml
<h2><?php echo $this->title ?></h2>

Leave a Reply

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