By default error pages gets the default layout of our application based on Zend Framework 2 and inject it’s own content.
Sometimes default layout has some features placed on it, which should not be presented on the error page. Especially when we would like to have minimalistic and tiny error pages.
Unfortunatelly we don’t have any option to set dedicated error pages layout in view_manager section of module config.

But we can achieve it quite easily.
First step is to define layout which will be used by error pages in module.config.php

{...}
'view_manager' => array(
  'template_map' => array(
     'layout/error' => __DIR__ . '/../view/layout/error.phtml',
{...}

Then we can force all error pages to use defined layout in Module.php

function onBootstrap(EventInterface $e) {
  $application = $e->getApplication();
  $eventManager = $application->getEventManager();
  $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this,'onDispatchError'), 100);    
}

function onDispatchError(MvcEvent $e) {
  $viewModel = $e->getViewModel();
  $viewModel->setTemplate('layout/error');
}

And that’s it. Now our error pages will be rendered within own error template.

Zend Framework 2: custom layout for error pages
Tagged on:                 

2 thoughts on “Zend Framework 2: custom layout for error pages

  • 2016-07-25 at 13:22
    Permalink

    Hello,
    thanks for presenting that solution. I have a problem though. How do I get all the original generated variables into the new layout? I know that I can use “setVariables()” on the view model, but where do I get the exact same variables that where used in the default layout?

    thanks

    Reply
    • 2016-07-28 at 20:11
      Permalink

      Replying to myself: Problem solved! There was no problem actually 😀

      Reply

Leave a Reply to Serge Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social Widgets powered by AB-WebLog.com.