phpzend-frameworkerror-handlingzend-viewzend-controller

Zend 2 define error page for controller


I have a module with several controllers. I want to use the normal error page for all controllers except for one.

Is it possible to define a error page that is only used if an exception is thrown in a certain controller ?

That is how the module config looks like :

'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions'       => true,
    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
    'template_map' => array(
        'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        'layout/header'           => __DIR__ . '/../view/layout/header.phtml',
        'layout/footer'           => __DIR__ . '/../view/layout/footer.phtml',
        'layout/sidebar'          => __DIR__ . '/../view/layout/sidebar.phtml',
        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'pagination/sliding'      => __DIR__ . '/../view/pagination/sliding.phtml',
        'error/404'               => __DIR__ . '/../view/error/404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
        __DIR__ . '/../view',
    ),
),

I know i can achieve something like that by putting this controller in a extra module and define a error page for this module, but i don't want to split my project over several modules.


Solution

  • Found a solution for my problem :

    Define the error template in the template_map :

        'template_map' => array(
              ...
              'error/controller'      => __DIR__ . '/../view/error/controller/index.phtml',
        ),
    

    Set the template in the controller construct method :

    public function __construct()
    {  
          $this->getServiceLocator()->get('ViewManager')->getExceptionStrategy()->setExceptionTemplate('error/controller');
    }