Yii widget使用
2014-04-04 22:27 youxin 阅读(851) 评论(0) 编辑 收藏 举报关于widgets,他们在yii中的关系如下
system.web.widgets 系统自带最基本的widget
zii.widgets 是基本扩展
zii.widgets.grid 是基本扩展的重要分支
zii.widgets.jui 是插件扩展
CWidget:http://www.yiiframework.com/doc/api/1.1/CWidget/
CWidget is the base class for widgets.
A widget is a self-contained component that may generate presentation based on model data. It can be viewed as a micro-controller that embeds into the controller-managed views.
Compared with controller, a widget has neither actions nor filters.
Usage is described at CBaseController and CBaseController::widget.
下面以一个随机广告图片为例说明Yii中Widget的用法
1. 调用Widget
- <?php $this->widget('WidgetName'); ?>
或者
- <?php $widget=$this->beginWidget('path.to.WidgetClass'); ?>
- ...可能会由小物件获取的内容主体...
- <?php $this->endWidget(); ?>
- <?php $userId = 1; ?>
- <?php $this->widget('WidgetName',array('userId'=>$userId)); ?>
参数userId自动映射到Widget类的同名属性,所以在定义Widget时,别忘记了声明该属性。
2. 创建Widget
自定义Widget类要继承CWidget,覆盖方法run
- <?php
- class BannerMagic extends CWidget {
- public function run(){
- }
- }
或者:
- class MyWidget extends CWidget {
- public function init() {
- // 此方法会被 CController::beginWidget() 调用
- }
- public function run() {
- // 此方法会被 CController::endWidget() 调用
- }
- }
下面是是BannerMagicWidget实现
- <?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,
- ));
- }
- }
存储到protected\components\BannerMagicWidget.php
对应的view文件可能的内容如下:
- <img src="images/adverts/<?php echo $advert; ?>" alt="whatever" />
存储到protected\components\views\bannermagic.php
3. 调用该Widget
- <?php $this->widget('BannerMagicWidget'); ?>
转自:http://koda.iteye.com/blog/1134606
yii dropdownlisthttp://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))