Create Widget In Yii

I learned “How To Create Widget” in yii.
Just i created welcome widget for my application.

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

01 //Welcomewidget .php
02 <?php
03 class Welcomewidget extends CWidget{
04     public $message;
05     public function init(){
06         $this->message=array(
07             'Hai',
08             'Yess It Is',
09             'How are you?',
10             'How is going life?'
11         );
13     }
14     public function run(){
15         $id=rand(0,3);
16         $this->render("displaymessage",array('id'=>$id));   
17     }
18 }
19 ?>

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

1 //displaymessage .php
2 <div  style="float: right;
3          padding-right: 50px;
4          padding-top: 12px;
5          font-size: 30px;">
6 <?php
7     echo $this->message[$id];
8 ?>
9 </div>

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

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *