How to use default layout for error pages instead of errorXXX views

4 0
3
Viewed: 47 519 times
Version: Unknown (update)
Category: Tutorials
    Written by: idle sign idle sign
    Updated by: Yang He Yang He
    Created: Sep 23, 2009
    Updated: 14 years ago

    You are viewing revision #3 of this wiki article.
    This version may not be up to date with the latest version.
    You may want to view the differences to the latest version or see the changes made in this revision.

    « previous (#2)next (#4) »

    The issue is covered in "The Definite Guide to Yii" (Error Handling - Handling Errors Using an Action).

    First we need to adjust application configuration as follows:

    return array(
        ......
        'components'=>array(
            'errorHandler'=>array(
                'errorAction'=>'mycontroller/error',
            ),
        ),
    );
    

    Here in the line "'errorAction'=>'mycontroller/error'" we define controller and its action, which should be used in case of an error ('mycontroller' - the controller, 'error' - the action).

    Next we define 'error' action in 'mycontroller' controller:

    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;
        if ($error)
    	$this->render('error', array('error'=>$error));
        else
    	throw new CHttpException(404, 'Page not found.');
    }
    

    Here if the action is triggered by an error we render 'error' view of 'mycontroller' ('/protected/views/mycontroller/error.php'), if not - we trigger 404 error manually.

    The last step is to setup our error view. It could be as follows:

    <?php $this->pageTitle=Yii::app()->name . ' - ' .$error['code']; ?>
    <h2>Error <?php echo $error['code'] ?></h2>
    <div>
        <?php echo $error['message']; ?>
    </div>
    

    Now all application errors are rendered using the default application layout.

    Links ΒΆ

    Chinese version