Yii2 How to pass a model instance to the main layout?
I have a bootstrap boot mod that will fire when the user clicks on the Change password navBar menu.
I have included the modal in the footer. But how to pass ChangePassword model instance
to the footer layout file?
Can it be beforeRender Or EVENT_BEFORE_RENDER
used? If so, how?
As suggested, I added generic code to / config / bootstrap.php:
yii\base\Event::on(yii\base\View::className(), yii\base\View::EVENT_BEFORE_RENDER, function() {
$modelChangePassword = new frontend\models\ChangePassword;
$this->view->params['modelChangePassword'] = $modelChangePassword;
});
But this gives an error Using $this when not in object context
.
source to share
You can pass it through View params :
Add this to your controller before the render view:
$this->view->params['model'] = $model;
...
$this->render(...); // this will render your view including main layout
Then use like this:
$model = $this->params['model'];
Update:
If you want to globally for all application controllers, you can use events:
use Yii;
use yii\base\Event;
use yii\web\View;
...
Event::on(View::className(), View::EVENT_BEFORE_RENDER, function() {
...
Yii::$app->view->params['model'] = $model;
});
Place this code in the bootstrap of your application or, for example, in a generic parent controller.
Official documents:
source to share