October 21, 2013

9:26 am
In this tutorial, we are going to discuss about How to setting the separate layout for the error pages based on the Auth Status with CakePHP. By default, CakePHP error pages load within the default layout. This is enough for most of the applications. But in some applications we need a separate layout for logged in users. So here I'm going to explain about how to set the separate layout for the error pages based on the Auth status with CakePHP.

For example, the navigation changes when a user logged in. Basically including the proper elements based in the user's login status. But for the some projects, the entire layout needs to be changed based on the user status. Therefore I needed to find a way to be sure the proper layout was loaded when 404 errors appeared.

To achieve this, we need to create an app_error.php file in our /app directory. Our 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.

<?php
class AppError extends ErrorHandler {
    function error404($params) {
            if( !$this->controller->Auth->User() ){
                $this->controller->layout = "guest";
            }
            parent::error404($params);
    }
}

0 comments:

Post a Comment