Zend Framework: How To Disable A View In An Action
Posted on September 17th, 2008 in PHP, Web Development, Zend Framework | 3 Comments »
Sometimes, especially when just testing things out, I don’t want to go to the trouble of having to create view script for my Controller Action and instead I just want to print something to the screen right from my Controller Action function. I guess because it’s sort of hard to find out how to do this in the ZF Documentation this is one of the most common questions I get asked – even from somewhat seasoned developers. The answer is in the Controller documentation and it’s easy to think that you ought to search under the View documentation to figure out how to turn this stuff off. Whatever the case, here’s the trick.
In the action of your Controller, via your Zend Controller Action Helper Broker, call the setNoRender() function of your viewRenderer passing true as the parameter like this:
[php]
require_once('Zend/Controller/Action.php');
class SiteController extends Zend_Controller_Action {
public function indexAction() {
$this->_helper->viewRenderer->setNoRender(true);
echo “Hello World!”;
}
}
?>
[/php]
If you want to disable the View rendering for all of your actions, just call the setNoRender() function in your Controller’s init() function and none of the actions in your controller will render views. If you want to kill the entire idea of automatically rendering views in your application, you can globally disable the viewRenderer by setting the noViewRenderer parameter to true with your Front Controller in your bootstrap file – prior to calling dispatch(). Your code might look like this:
[php]
// This is your bootstrap file:
// Perhaps your index.php file in your public directory
$frontController = Zend_Controller_Front::getInstance();
$frontController->setParam(‘noViewRenderer’, true);
?>
[/php]
3 Responses
Handy, thanks.
But how would you kill the layout completely?
Like if you just want to return something or provide a JSON response etc.. ?
I just want to echo out a value, but my main layout keeps rendering as well… :/
You can disable both the view and the layout like this.
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
Yet another approach:
$this->getHelper(‘viewRenderer’)->setNoRender();