Tuesday, May 29, 2012

Setting custom layout for 404 error page in YII Framework

If you want to set a custom layout for 404 error page in YII Framework, you can do the following:

1. Modify config/main.php
'components'=>array(
...
        'errorHandler'=>array(
            'errorAction' => 'site/error'
        ),
...
),
The site/error is where the error page resides.  It is in the views/site/error.php page.  In order for the pages in views/site/ to show, it needs the controller, and SiteController located in /controllers/SiteController.php.  

controllers/SiteController.php
    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;

        if( $error )
        {
            $this -> render( 'error', array( 'error' => $error ) );
        }
    }

If you do not want to use the site controller, you can create a new view and controller folder.  For example, you can create views/general/error.php and controllers/GeneralController.php and modify 'errorAction' => 'general/error'.  


controllers/GeneralController.php

<?php 
 class GeneralController extends Controller {
    public $layout='main_general';  //layout goes here    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;

        if( $error )
        {
            $this -> render( 'error', array( 'error' => $error ) );
        }
    }   ?>
the main_general should be located in either WebRoot/themes/ThemeName
As indicated in the link here http://www.yiiframework.com/doc/guide/1.1/en/topics.error
'main_general' (layout) is either located in 3 location.  
It is either 
1. in your main theme view folder /WebRoot/themes/ThemeName/views/main_general.php
2. in the WebRoot/protected/views/main_general.php (default)
3. in yii/framework/views - the standard system view directory provided by the Yii framework.


views/site/error.php or views/general/error.php
<div class="errorSummary">
    <p>
    Sorry, it seems like a(n) <?= $error['code']; ?> error has occured during your request.
    </p>

    <p><strong>Message:</strong> <?= $error['message']; ?></p>
</div>




2 comments:

ThA-B said...

Grrr, at last a normal explanation on how to do it :) Thank you.

Nuvem K said...

Couldn't agree more. ;) Cheers.