Yii 2 Quick access to the controller from the view

So, in Yii 1, in the view file, you can access the properties / actions of the controller using $this->action() or $this->property .

In Yii 2, the only way I see this is to use Yii::$app->controller->property or Yii::$app->controller->action() . I am one of those who does not want to write more code than necessary, so I was wondering if there is a shorter way to do this.

+5
source share
2 answers

For the view controller, there is basically a “context” where the visualization of this view is called.

There is a special property for getting the current controller, and it is called like this: context .

Example: $this->context

Official documents:

+14
source

\Yii::$app->controller is actually the only "real" way to do this.

There is a way to write a little less, I don’t know if it is worth the effort:

 public function actionWhatever() { return $this->render('view', ['controller' => $this]); } 

Then you have $controller -variable.

0
source

All Articles