Yii create your own widget method instance-random ad image

Source: Internet
Author: User
Tags php class yii

1. Call widgets

The code is as follows: Copy code
<? Php $ this-> widget ('widgetname');?>



Or

The code is as follows: Copy code
<? Php $ widget = $ this-> beginWidget ('path. to. Widgetclass');?>



... Content subject that may be obtained by small objects...

The code is as follows: Copy code

<? Php $ this-> endWidget ();?>



You can also pass parameters to the Widget class.

The code is as follows: Copy code

<? Php $ userId = 1;?>
<? Php $ this-> widget ('widgetname', array ('userid' => $ userId);?>


The userId parameter is automatically mapped to the same name property of the Widget class. Therefore, when defining a Widget, do not forget to declare this property.

2. Create a Widget

The custom Widget class inherits the CWidget and overwrites the run method.

The code is as follows: Copy code

<? Php
Class BannerMagic extends CWidget {
Public function run (){
}
}


Or:

The code is as follows: Copy code

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 implementation of BannerMagicWidget.

The code is as follows: Copy code

<? Php class BannerMagicWidget extends CWidget {
Public function run (){
$ Random = rand (1, 3 );
If ($ random = 1 ){
$ Advert = "advert1.jpg ";
} Else if ($ random = 2 ){
$ Advert = "advert2.jpg ";
} Else {
$ Advert = "advert3.jpg ";
}
$ This-> render ('bannermagic ', array (
"Advert" => $ advert,
));
}
}


Stored in protectedcomponentsBannerMagicWidget. php

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

The code is as follows: Copy code

"Alt =" whatever "/>



Storage to protectedcomponentsviewsbannermagic. php

3. Call this Widget

The code is as follows: Copy code

<? Php $ this-> widget ('bannermagicwidget ');?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.