Access controller object from widget's view

In the documentation, it says :

I’m in the widget’s view, so if I use $this->context from the view, I will access the widget. So far so good.

But, still in the widget’s view, how could I access the controller object that called (created) the widget in the first place ? It seems that in Yii 1.1, that was possible … so why not in Yii 2.0 ?

You can forward the data you need in the widget and the view can use this data from the widget.

Another possibility is to use Yii::app->controller, but on this way your view based on a unkown controller.

But than your view get a high dependency, also I think the first way is the better option.

That’s what I did, and it works. Thank you !

For the sake of others, here’s what I did in more details. The name of my widget is LanguageSelector. I added a public property in this widget called “$callingController”. From the “base” view, the one called by the controller (and not the widget’s view), I call the widget in this way :

echo LanguageSelector::widget(['callingcontroller'=>$this->context]);

Here $this->context is the controller.

Then, from the widget’s view, I can access the controller in this way :

$controller = $this->context->callingcontroller;

Here $this->context is the widget, and $this->context->callingcontroller is the controller.

Those explanations are addressed at newbies like me … :)

What you should remember:

Be carefully with passing the controller to the widget.

The widget get more dependency to a controller implementation and that does not follow the SOLID principle.

So, if you will use the widget in another view, you will get another controller, too!