Skip to content

How to Create A Custom Widget in Yii Framework ?

Last updated on February 10, 2018

Yii is a wonderful framework that gives generated codes for the developer.in here I will show you how to create a Custom widget in Yii.

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()run() methods get called automatically.

widget('path.to.MyWidget'); ?>

Where should I put my custom widget files in Yii framework?

I think the common practice is to put the widget Folder in extensions folder with js & CSS files in a folder named asset. In the PHP class file, you do initialization first by publishing the asset with Yii asset manager.

The file structure may be like
/protected/extensions/MyWidgetdir/assets/
/protected/extensions/MyWidgetdir/views/
/protected/extensions/MyWidgetdir/MyWidget.php

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments