Setting layout in error pages based on Auth status with CakePHP

CakePHP error pages load within the default layout. This works most of the time, but for some applications, I have a different layout file for logged in users. For example, the navigation changes when a user is logged in. Normally including the proper elements based on the user’s login status would be sufficient, but for a recent project, the entire layout changes based on the user status. Therefore I needed to find a way to be sure the proper layout was loaded when 404 errors appeared.

First thing to do is create an app_error.php file in your /app directory. Your AppError class should extend the ErrorHandler class. Now extend the error404 method. You’ll have a reference to the controller via $this->controller so that you can access the Auth component. So just see if we have a valid logged in user, and if not, set the layout to ‘guest’, or whatever your layout happens to be named.

Be sure to call the parent method, passing in the $params variable to be sure the error is handled properly by the ErrorHandler’s error404 method.

1
2
3
4
5
6
7
8
9
10
11
<?php
class AppError extends ErrorHandler {

    function error404($params) {
            if( !$this->controller->Auth->User() ){
                $this->controller->layout = "guest";
            }
            parent::error404($params);
    }

}

One Comment

  1. [...] Setting layout in error pages based on Auth status with CakePHP [...]

Leave a Reply to on Planet CakePHP « Afzet Inc.