Yii之widget专题
作者:zccst
关于widgets,他们在yii中的关系如下
system.web.widgets 系统自带最基本的widget
zii.widgets 是基本扩展
zii.widgets.grid 是基本扩展的重要分支
zii.widgets.jui 是插件扩展
一,system.web.widgets
包括:
CActiveForm
CAutoComplete
CClipWidget
CContentDecorator
CFilterWidget
CFlexWidget
CHtmlPurifier
CInputWidget
CMarkdown
CMaskedTextField
CMultiFileUpload
COutputCache
COutputProcessor
CStarRating
CTabView
CTextHighlighter
CTreeView
CWidget
1,CWidget
批注:CWidget是所有Widget的基类。CWidget是自包含组件,可以看出是MVC的简略版,CWidget相比Controller,既没有actions,也没有filters。
实现细节可参考 CBaseController and CBaseController::widget.
CWidget
2,CWidget实例(右侧页面)
CWidget是components下一个独立的文件夹(路径是:../components/widgets/)
有自己的controller和views。其中controller继承自CWidget,习惯命名为XXWidget.php(XXWidget extends CWidget)。
XXWidget.php有两种写法
/********** 方式一: **********/public function run() { //逻辑 $this->render("fail_basic", array('summaryIdcs' => $summaryIdcs));}/********** 方式二: **********/<?php $form=$this->beginWidget('CActiveForm', array('id'=>'user-form','enableAjaxValidation'=>false,'htmlOptions'=>array('enctype'=>'multipart/form-data'),)); ?>..body content that may be captured by the widget...<?php $this->endWidget(); ?>//或<?php $this->widget('path.to.WidgetClass'); ?>class testWidget extends CWidget{ public function init() { //当视图中执行$this->beginWidget()时候会执行这个方法 //可以在这里进行查询数据操作 } public function run() { //当视图中执行$this->endWidget()的时候会执行这个方法 //可以在这里进行渲染试图的操作,注意这里提到的视图是widget的视图 //注意widget的视图是放在跟widget同级的views目录下面,例如下面的视图会放置在 // /protected/widget/test/views/test.php $this->render('test', array( 'str'=>'WIDGET视图变量', )); }}//在../components/RecentComments.php中Yii::import('zii.widgets.CPortlet');class RecentComments extends CPortlet{public $title='Recent Comments';public $maxComments=10;public function getRecentComments(){return Comment::model()->findRecentComments($this->maxComments);}protected function renderContent(){$this->render('recentComments');}}//在../components/view/recentComments.php中<ul><?php foreach($this->getRecentComments() as $comment): ?><li><?php echo $comment->authorLink; ?> on<?php echo CHtml::link(CHtml::encode($comment->post->title), $comment->getUrl()); ?></li><?php endforeach; ?></ul>