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();?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值