Yii passing parameters to widget

Shahid Karimi picture Shahid Karimi · Feb 15, 2013 · Viewed 11.1k times · Source

Sorry if I am using wrong keyword. Might be I did not get sufficient information due to wrong keyword.

we create widget in Yii by this way:

class streamList extends CWidget {
  //do some stuff
}

Also, we use this widget anywhere as

$this->widget("application.components.widget.streamList");

How can we write the widget in such a way that it accepts parameter(s) as

$this->widget("application.components.widget.streamList",array('title'=>'Posts');

I googled but did not solve. Please help, thank in advance.

Edit log: Also, how can we define default parameter value to 'titile'? I tried public $title = Shk::getTitle(), but it did not work.

Answer

topher picture topher · Feb 15, 2013

Use

class StreamList extends CWidget {
    //do some stuff
    public $title;
}

Any attributes can be initialized with default values and overwritten by

$this->widget("application.components.widget.StreamList",array('title'=>'Posts',.....)

EDIT

You can't initialize class attributes with functions. An explanation is given here. An option is to check whether $title is set and if not set it to Shk::getTitle() in the init() method like

public function init(){
    ....
    if(!isset($this->title) || !$this->title)
        $this->title=Shk::getTitle();
    ....
}

P.S for consistency it's better to Capitalize your class names.