Stefan Dunn
Stefan Dunn

Reputation: 5513

Yii 2 Quicker way to access controller from view

So in Yii 1, in the view file you could access the Controller's properties / actions using $this->action() or $this->property.

In Yii 2, the only way I can see this possible is using Yii::$app->controller->property or Yii::$app->controller->action(). I am one for not wanting to write more code than is necessary, so I was wondering if there's a shorter method of doing it.

Upvotes: 7

Views: 9339

Answers (2)

arogachev
arogachev

Reputation: 33548

For view controller is basically "context" where render of this view was called.

There is special property to get current related controller from view and it's called exactly like this: context.

Example: $this->context

Official docs:

Upvotes: 16

Blizz
Blizz

Reputation: 8408

\Yii::$app->controller in indeed the only "real" way to do so.

There is a way of writing a bit less, dunno if it is worth the effort:

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

Then in your view you have a $controller-variable.

Upvotes: 0

Related Questions