How to set layout for errorhandler dynamically wit

2019-07-21 12:05发布

问题:

I am new in Yii2,

When I started creating a website, i found that you can set ErrorAction in configuration like this

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

        ],

That error using layout from layout/main.php. That layout was used when guest visit the page that located in 'view/site'. But when the user log in the view page locate in different folder which is 'view/band' the layout become totally different and using 'layout/BandLayout'. I know that you can change layout dynamically in controller like i did in BandController

public $layout ='BandLayout';

That will change the entire layout in 'view/band'. But when there is an error like '404' the layout still using layout from layout/main.php. I have done some searching but the solution using init() in module. Since i have not learn module, how do I set layout for error layout in controller?

Thank you

回答1:

You should change layout in SiteController, you could use beforeAction, e.g. :

public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        // change layout for error action
        if ($action->id=='error')
             $this->layout ='BandLayout';
        return true;
    } else {
        return false;
    }
}


标签: php yii2