Search code examples
cakephpcakephp-2.9

Is it possible to show default layout in error pages?


I want to style my app from scratch so I've created a brand new layout and assigned it as default:

class AppController extends Controller {

    public $components = array(
        'DebugKit.Toolbar',
    );

    public function beforeRender() {
        parent::beforeRender();

        $this->layout = 'app';
    }
}

However, it seems that it also affects the internal error pages generated by CakePHP that I need for development:

Actual

Is there a way to make such pages use app\View\Layouts\default.ctp instead of app.ctp?

Intended


Solution

  • You can do this by creating a custom exception renderer:-

    // app/Lib/Error/AppExceptionRenderer.php
    class AppExceptionRenderer extends ExceptionRenderer {
    
        public function render() {
            $this->controller->layout = 'default';
            parent::render();
        }
    
    }
    

    Then in app/Config/core.php make sure you tell Cake to use your AppExceptionRenderer class for handling exceptions:-

    Configure::write('Exception', array(
        'handler' => 'ErrorHandler::handleException',
        'renderer' => 'AppExceptionRenderer',
        'log' => true
    ));
    

    Using a custom exception renderer gives you greater flexibility over how you handle exceptions in your app.

    Finally, move the custom layout definition from \AppController::beforeRender to \AppController::beforeFilter so it runs earlier and can be overridden in case of error:

    class AppController extends Controller {
        public function beforeFilter() {
            parent::beforeFilter();
            $this->layout = 'app';
        }
    }