7

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.

Chinmay Waghmare
  • 5,368
  • 2
  • 43
  • 68

1 Answers1

9

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:

arogachev
  • 33,150
  • 7
  • 114
  • 117
  • I dont want to do that in every controller. Isn't there a common place where I can put this which will be available throughout the application? – Chinmay Waghmare May 02 '15 at 05:07
  • I am getting the following error when I put it in bootstrap file: Using $this when not in object context. I have update the question Could you please have a look. – Chinmay Waghmare May 02 '15 at 05:22