Give all of your error messages a different layout

By default CakePHP will use the default.ctp layout to display any error messages.

In some cases this may not be desirable as your default.ctp might contain navigational and design elements, CSS and JS files, which really take away from the way the error message is displayed.

Usually an error message should be displayed in a clean and simple layout that only focuses on the error itself.

Thankfully, the remedy for this is pretty simple…

First, create a new layout and call it error.ctp (place in the app/views/layouts, of course).

Then add this to your App Controller:


function beforeRender () {  
       $this->_setErrorLayout(); 
}

function _setErrorLayout() {
    if($this->name == 'CakeError') {
        $this->layout = 'error';
    }
}

That’s all folks.

P.S. Note, this is different than modifying error message views. For instructions on that, please look at the helpful instructions in the actual error message.

10 thoughts on “Give all of your error messages a different layout

  1. That’s interesting. Aren’t there some cases where ErrorHandler won’t initialize a controller, or won’t invoke every AppController callback?

  2. @Matthew Harris

    With debug 0, the debugger is not invoked, but the rest works the same for any debug level. I don’t know of any other cases, please let me know if you find one.

  3. Thank u very much for your tips.
    This is what i have been looking for and now i found it after i spent a couple hours searching it in google.

    There is one more thing I want to know about it. How i set a different layout (for the error of course) for different user.
    Example :
    For public error (for user that not authenticated or not log in) i prefer use of “public_error” layout, but for user member (user that log in to member area) i prefer use of “member_error” layout.
    Can i implement this in cake ?

    btw : Your blog is very usefull information of cake !

  4. @Abu Zaid

    If you are using cake’s Auth, you can do a simple if() and then set appropriate layout based on whether the user is logged in or not.

    And thanks for the compliment ;)

  5. Great,
    i do it like this :

    if ($this->name == 'CakeError') {
    	if ($this->Auth->user('status')=='member') {
    		$this->layout = 'member';
    	} else if ($this->Auth->user('status')=='admin') {
    		$this->layout = 'admin';
    	} else $this->layout = 'default';
    }
    

    THanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s