widgets
widgets
widgets有挂件、微件的意思
简单的说就是一个微型的控制器
- widgets
- 创建目录
- 创建widgets
- 创建widgets视图
- 使用
创建目录
1、在项目目录下创建 widgets
目录
2、下widgets目录下创建 views
目录
创建widgets
userWidget
class userWidget extends CWidget{public $num = 20;public function init() {}public function run() {$users = $this->getUsers();$this->render('userwidget',array('users'=>$users));}protected function getUsers(){return Yii::app()->db->createCommand()->select('id,username,ctime')->from('user')->limit($this->num)->queryAll();}
}
userWidget2
class userWidget2 extends CWidget{public function init() {echo CHtml::beginForm("", "POST");}public function input($name,$value = "",$label = ""){$label = $label===""?$name:$label;echo CHtml::label($label.':', $name);echo CHtml::textField($name,$value);}public function run() {echo CHtml::endForm();}
}
创建widgets视图
userwidget.php
<table><tr><th>id</th><th>username</th><th>date</th></tr>
<?php foreach($users as $v):?><tr><td><?=$v['id'];?></td><td><?=$v['username'];?></td><td><?=$v['ctime'];?></td></tr>
<?php endforeach;?>
</table>
使用
需要注意的是:
1、widget渲染的视图,$this指向当前widget,要想使用当前controller就要 Yii::App()->controller
2、传递的参数 可以初始化对应的 对应的公开属性
3、widgets的第二种执行方式,beginWidget对应init(),endWidget对应run()
<h1>调用当前controller测试</h1>
<?php echo Yii::app()->controller->createUrl("test");?><h1>第一种使用方式</h1>
<?php $this->widget('application.widgets.userWidget',array('num'=>6));?><h2>第二种使用方式</h2>
<?php $form = $this->beginWidget('application.widgets.userWidget2');?>
<?php $form->input('username');?>
<?php $this->endWidget();?>