Create Widget In Yii

I have learned and created new welcome widget for my application. I have shared my working experience here.

What is widget

Widget is a small gadget.An application or a component of an interface, that enables a user to perform a function or access a service.

Create Widget Class

//Welcomewidget .php
class Welcomewidget extends CWidget{
    public $message;
    public function init()
            'Yess It Is',
            'How are you?',
            'How is going life?'
    public function run()

Create one class "Welcomewidget" with extends CWidget. Then i created one global variable for this widget. that is called "$message". I stored display messages in this variables in init() method. When run this class It called "displaymessage" file. It should be inside "Views" folder and i display message inside view file.

Create Widget View

//displaymessage .php
<div style="float: right;padding-right: 50px;padding-top: 12px;font-size: 30px;">
    echo $this->message[$id];

This "displaymessage" file called by "Welcomewidget" class. Here i get and display the message using global $message variables and random number to get message from array.

Call Widget function

<div id="displaymessage">
    <?php $this->widget('Welcomewidget'); ?>

In my "site/layout/main.php", I included this code. It is displaying message on every new page load.
Widget is a powerful and simple option in YII.

  • Pingback: Yii Tag Cloud Widget | BSOURCECODE()

  • Daniel

    This article is very clean and helpful.

  • Deepak


    Can you please help me with the folder structure Like where is the Welcomewidget .php file ,
    Where is the Welcomewidget .php file