Yii Custom Widget Simple Example

Last updated:

Simplest possible way to get a Custom Widget going:

class MyWidget extends CWidget{
    //init() method is called automatically before all others 
    public function init(){
        /*you can set initial default values and other stuff here.
         * it's also a good place to register any CSS or Javascript your
         * widget may need. */  
    public function run(){
        /* here stuff gets actually done: you can echo the actual HTML that
         * makes up your widget.*/

Then, in a view, you can instantiate it like this: the init() and run() methods get called automatically.

<?php $this->widget('path.to.MyWidget'); ?>

Dialogue & Discussion