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

喜夏-厌秋 提交于 2019-12-10 13:40:00

问题


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.


回答1:


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()


来源:https://stackoverflow.com/questions/29998442/yii2-how-to-pass-the-model-instance-to-the-main-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!