3

For setting error action I added this code in my controller

public function beforeAction($action) {
    if ($action->id == 'error')
        $this->layout = 'iframe-main.php';

    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}

But its not working.Error layout is displaying in default layout

Jackhad
  • 331
  • 1
  • 6
  • 16
  • Similar question here: http://stackoverflow.com/questions/27573826/how-to-set-layout-for-errorhandler-dynamically-without-module – robsch May 03 '17 at 08:57

4 Answers4

6

You could use Yii2 official yii\web\ErrorAction to handle error in controller:

/**
 * {@inheritdoc}
 */
public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
            'layout' => 'login',
        ],
    ];
}

Note that we could set the layout property for changing layout for error view.

https://www.yiiframework.com/doc/api/2.0/yii-web-erroraction

Nick Tsai
  • 2,961
  • 28
  • 32
3

Add to your config:

'components' => ['errorHandler' => [
        'errorAction' => 'site/error',
    ],

Create controller if not exists: SiteController.php with content:

namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actionError()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            $this->layout = 'yourNewLayout';
            return $this->render('error', ['exception' => $exception]);
        }
    }
}

And simplest view site/error.php:

<?php 
    use yii\helpers\Html; 
?>
<div class="site-error">
        <?= Html::encode($exception->getMessage()) ?>
</div>

Tested on Yii2. More information in documentation http://www.yiiframework.com/doc-2.0/guide-runtime-handling-errors.html#using-error-handler

Yury
  • 99
  • 3
2

Try this:

public function beforeAction($action) {
    if (parent::beforeAction($action)) {
        // change layout for error action
        if ($action->id=='error') $this->layout ='iframe-main';
        return true;
    } else {
        return false;
    }
}
robsch
  • 8,466
  • 8
  • 56
  • 87
jithin
  • 882
  • 8
  • 16
  • ahh..its my mistake..I add this in my controller instead of sitecontroller.php.Working fine! Thanks!! :) – Jackhad Jun 09 '16 at 04:19
0

In your actionError() of SiteController Just add the default layout name

class SiteController extends Controller
{

public function actionError()
    {
        $this->layout='defaultLayoutName';
           //rest of the code goes here
    }
}
vijay nathji
  • 1,490
  • 11
  • 22