问题
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