mfecteau
(Matthieufecteau)
October 29, 2014, 2:05am
1
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 ?
boehsermoe
(Boehsermoe)
October 29, 2014, 6:44am
2
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.
mfecteau
(Matthieufecteau)
October 29, 2014, 3:49pm
3
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 …
boehsermoe
(Boehsermoe)
October 30, 2014, 6:30am
4
mfecteau:
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!