Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set layout for errorhandler dynamically without module

Tags:

php

yii2

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

like image 405
Hussein Amb Avatar asked Nov 20 '25 23:11

Hussein Amb


1 Answers

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;
    }
}
like image 91
soju Avatar answered Nov 23 '25 14:11

soju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!