Michaël Gallego

This is my blog. What can you expect here? Well... Zend Framework 2, Amazon AWS...

Twitter

Google+

LinkedIn

Github

Last.fm

How to override error layout in ZF2 app

You may want to change your application layout in case of errors (for 404 error for example). Unfortunately, Zend Framework 2 makes this unintuitive. At the very beginning of the Zend Framework 2 development, you could simply override an “ErrorController” and define your own layout.

But this has been changed before 2.0 official release, and now you must listen to the EVENT_DISPATCH_ERROR event:

$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function(MvcEvent $event) {
    $viewModel = $event->getViewModel();
    $viewModel->setTemplate('layout/error-layout');
}, -200);

UPDATE

Jurian Sluiman outlined a simpler solution that does not involve events. In your 404.phtml and/or error.phtml views, you can simply write this simple code:

<?php $this->layout('layout/error-layout'); ?>

This works because in a views hierarchy, the inner template (referred as child view) is always rendered BEFORE the layout. The only downside to this approach is that you need to change the layout in every template that need to use the alternate layout (while with events, we globally set it for every DISPATCH_ERROR event that is triggered).