Search code examples
error-handlingzend-framework2viewmodelcustom-error-pagescustom-error-handling

How to pass variables to the error view script in Zend Framework 2?


I catch the framework specific exceptions as follows:

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
    ...
    $sharedManager = $e->getApplication()
        ->getEventManager()
        ->getSharedManager();
    $sm = $e->getApplication()->getServiceManager();
    $sharedManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_DISPATCH_ERROR, 
        function ($e) use($sm) {
            if ($e->getParam('exception')) {
                $sm->get('Logger')
                    ->crit($e->getParam('exception'));
            }
            // trying to pass a variable
            $e->getViewModel()->setVariable('foo', 'bar');
        });
}

When I then try to access $foo in the /module/Application/view/error/index.phtml I get a Notice: Undefined variable: foo.

How to pass a variable to the error view script and access it there?


Solution

  • From within the onBootstrap it passes the variable to the layout.

    Try this:

    $this->layout()->foo