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


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(

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));
    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>
    <?php echo $error['message']; ?>

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

Total 1 comment

#1299 report it
phpdevmd at 2009/09/25 05:12am

If you want to handle errors in SiteController, then in config it should be 'errorAction'=>'site/error', and path to view is '/protected/views/site/error.php' Also, if you are using 'backend' as admin area, then copy view file to '/protected/backend/views/site/error.php' and actionError() function to protected/backend/controllers/SiteController.php

Thanks for this great cookbook article. Yii makes so easy to handle complicated things!

Leave a comment

Please to leave your comment.

Write new article
  • Written by: idle sign
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +4 / -1
  • Viewed: 29,378 times
  • Created on: Sep 23, 2009
  • Last updated: Jun 30, 2012