SoFunction
Updated on 2025-04-04

Create your own Widget instance in Yii

This article describes the creation of your own Widget implementation method in Yii. Share it for your reference, as follows:

Here we use a random advertising image as an example to illustrate the usage of Widget in Yii

1. Call Widget

Copy the codeThe code is as follows:
<?php $this->widget('WidgetName'); ?>

or
&lt;?php $widget=$this-&gt;beginWidget(''); ?&gt;
...Content body that may be obtained by small objects...
&lt;?php $this-&gt;endWidget(); ?&gt;

You can also pass the parameters to the Widget class

<?php $userId = 1; ?>
<?php $this->widget('WidgetName',array('userId'=>$userId)); ?>

The parameter userId is automatically mapped to the property of the same name of the Widget class, so don't forget to declare the property when defining a Widget.

2. Create a Widget

Custom Widget class must inherit CWidget and override method run

<?php
class BannerMagic extends CWidget {
  public function run(){
  }
}

or:

class MyWidget extends CWidget {
  public function init() {
    // This method will be called by CController::beginWidget()  }
   public function run() {
    // This method will be called by CController::endWidget()  }
}

The following is the BannerMagicWidget implementation

<?php class BannerMagicWidget extends CWidget {
  public function run() {
   $random = rand(1,3);
   if ($random == 1) {
    $advert = "";
   } else if ($random == 2) {
    $advert = "";
   } else {
    $advert = "";
   } 
   $this->render('bannermagic',array(
    "advert"=>$advert,
   ));
  }
}

Store to protected\components\

The possible contents of the corresponding view file are as follows:

Copy the codeThe code is as follows:
<img src="images/adverts/<?php echo $advert; ?>" alt="whatever" />

Store to protected\components\views\

3. Call the Widget

Copy the codeThe code is as follows:
<?php $this->widget('BannerMagicWidget'); ?>

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.