Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 How to pass the model instance to the main layout?

I have a change password bootstrap modal which will get triggered when the user clicks on the Change password navBar menu.

I have included the modal in the footer. But how can I pass the ChangePassword model instance to the footer layout file?

Can beforeRender Or EVENT_BEFORE_RENDER be used? If yes, How?

As suggested, I have put the following code in common/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 its giving Using $this when not in object context error.

like image 281
Chinmay Waghmare Avatar asked May 02 '15 04:05

Chinmay Waghmare


1 Answers

You can pass it through View params:

Add this in controller before rendering view:

$this->view->params['model'] = $model;

...

$this->render(...); // this will render your view including main layout

Then use in view like that:

$model = $this->params['model'];

Update:

If you want it 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;
});

Put this code in application bootstrap or for example in common parent Controller.

Official docs:

  • Events
  • Event::on()
like image 111
arogachev Avatar answered Oct 20 '22 01:10

arogachev