CGridView基本结构与默认配置
在 Yii 自动生成的代码里,admin 界面常出现 CGridView 的身影。作为强大的数据展示表格控件,熟练运用它能显著加快开发进度。接下来将深入探索 CGridView 的基本使用方法。
为简化说明,代码基于 Yii demo 中的 blog 示例进行修改。首先涉及部分 MySQL 语句的调整。
drop table if exists `tbl_user`;
CREATE TABLE tbl_user
(
`user_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键',
`username` VARCHAR(128) NOT NULL comment '用户名',
`nickname` VARCHAR(128) NOT NULL comment '昵称',
`password` VARCHAR(128) NOT NULL comment '密码',
`email` VARCHAR(128) NOT NULL comment '邮箱',
`is_delete` tinyint not null default 0 comment '删除标志',
unique key(`username`),
primary key (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='用户表';
drop table if exists `tbl_post`;
CREATE TABLE tbl_post
(
`post_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键',
`title` VARCHAR(128) NOT NULL comment '标题',
`content` TEXT NOT NULL comment '文章内容',
`tags` TEXT comment '标签',
`status` INTEGER NOT NULL comment '状态,0 = 草稿,1 = 审核通过,-1 = 审核不通过,2 = 发布',
`create_time` INTEGER comment '创建时间',
`update_time` INTEGER comment '更新时间',
`author_id` INTEGER NOT NULL comment '作者',
`is_delete` tinyint not null default 0 comment '删除标志',
CONSTRAINT `post_ibfk_1` FOREIGN KEY (author_id)
REFERENCES tbl_user (`user_id`) ON DELETE CASCADE ON UPDATE RESTRICT,
primary key (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='日志表';
系统包含两个表:一个存储作者信息,另一个存储日志,其中日志表通过外键关联到用户表。两表均设有 is_delete 字段用于标记删除状态,0 表示未删除,1 表示已删除。观察由 gii 生成的 Post 类的 relation 方法。
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'author' => array(self::BELONGS_TO, 'User', 'author_id'),
);
}
其中的 author 外键以 BELONGS_TO 关系存在,符合预期设计。 上述铺垫完成后,查看自动生成的 Post 模型中 admin.php 文件内的 CGridView 代码。
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'post_id',
'title',
'content',
'tags',
'status',
'create_time',
'update_time',
'author_id',
'is_delete',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
无需额外编写代码,即可实现该控件的最基础使用。dataProvider 由 model 中的 search 函数提供数据源;filter 参数作用暂不明显;columns 控制各列展示;最后一项 CButtonColumn 提供了“查看”、“更新”和“删除”三个操作按钮。 接下来逐步对代码进行改造。
数据格式化与自定义列配置
利用 CGridView 展示经过处理的数据形式: 数据库原始数据往往不适合直接展示给用户,需经处理后才易于阅读。若不做修改,CGridView 会原样呈现数据库值。因此,应在相应字段进行处理。例如 is_delete 字段,数据库中存的是 0 和 1,直接阅读体验不佳,应改为展示“是”或“否”。参考以下代码,使用 array 结构,包含 name 和 value 两个键。name 对应 model 中的字段名,value 则是希望展示的内容,可写入 PHP 语句作为可执行代码。至此,是否意识到 value 具有极大的扩展性?若有疑问:若执行代码过长,难道都要写在 value 里?其实,完全可以在其他地方定义函数并在 value 中调用。
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'post_id',
'title',
'content',
'tags',
'status',
'create_time',
'update_time',
'author_id',
'is_delete',
array(
'name'=>'is_delete',
'value'=>'is_delete?"是":"否"' //value 是可以执行 php 语句的哦
)
array(
'class'=>'CButtonColumn',
),
),
)); ?>
此外,array 中还支持其他常用选项,以下是较为常见的配置方式(省略其余代码)。
array(
'name'=>'is_delete',
'value'=>'is_delete?"是":"否"' //value 是可以执行 php 语句的哦
'filter' => array(0=>'否',1=>'是'), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单
'htmlOptions'=>array('class'=>'delete'), //可以定义 html 选项,这里是定义了带一个 delete 的类
),
此前使用 name 指向 model 原有字段,若想展示自定义新内容,可使用 header 属性。
array(
'header'=>'备注',
'value'=> 'display your data'
),
引入 CCheckBoxColumn: 有时需要复选框以便选择每一行,此时可增加一列,使用 CCheckBoxColumn 类。
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'selectableRows' => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选
'class' => 'CCheckBoxColumn',//复选框
'headerHtmlOptions' => array('width'=>'18px'),//头部的 html 选项
'checkBoxHtmlOptions' => array('name' => 'myname','class'=>'myclass'), //复选框的 html 选项
),
'post_id',
'title',
'content',
'tags',
'status',
'create_time',
'update_time',
'author_id',
'is_delete',
array(
'name'=>'is_delete',
'value'=>'is_delete?"是":"否"', //value 是可以执行 php 语句的哦
'filter' => array(0=>'否',1=>'是'), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单
'htmlOptions'=>array('class'=>'delete'), //可以定义 html 选项,这里是定义了带一个 delete 的类
),
array(
'class'=>'CButtonColumn',
),
),
));
</code></pre>
调整 ButtonColumn:
注意到列表每项末尾的三个小图标吗?若不需要可直接删除;若只需保留其中某几个,可添加 template 参数。
<pre class="brush:php;"><code class="language-php">
array(
'class'=>'ButtonColumn',
'template'=>"{view} {update}",
),
</code></pre>
也可自定义按钮行为。
<pre class="brush:php;"><code class="language-php">
array(
'class'=>'ButtonColumn',
'template'=>"{view} {update} {print}",
'buttons'=>array(
'print'=>array(
'label'=>'打印',
'url'=>'Yii::app()->controller->createUrl("print", array("id"=>$data->post_id))',
'options'=>array("target"=>"_blank"),
),
),
),
</code></pre>
刷新时触发 Javascript:
若希望在每次搜索后触发某些 Javascript 逻辑,Yii 提供了此选项。只需编写函数并设置 afterAjaxUpdate 即可。注意,这仅在 ajax 请求完成后调用;若需在页面初始加载完成时调用,需另外添加到页面的 Javascript 中。
<pre class="brush:php;"><code class="language-php">
$js = <<<_JS_
function(){
alert('The ajax finish');
}
_JS_;
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'afterAjaxUpdate'=>$js, //看这里,ajax 之后调用的 javascript 在这里....
'columns'=>array(
array(
'selectableRows' => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选
'class' => 'CCheckBoxColumn',//复选框
'headerHtmlOptions' => array('width'=>'18px'),
'checkBoxHtmlOptions' => array('name' => 'myname','class'=>'myclass'),
),
....
</code></pre>
<h2>关联表字段模糊搜索实现方案</h2>添加关联表相关字段的搜索功能:
此处仅讨论“一对多”关联搜索。首先回顾数据库结构,tbl_post 表中有一个外键关联到 tbl_user 表,用于查找作者信息。建立数据库后,查看生成的 Yii 代码中 POST 模型的 relations 方法(忽略 comment 部分)。
<pre class="brush:php;"><code class="language-php">
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'post_id'),
'author' => array(self::BELONGS_TO, 'User', 'author_id'),
);
}
</code></pre>
可见 POST 和 USER 表可通过 author 键访问,例如 $model->author->nickname,且此为 BELONGS_TO 关系。
阐述至此,我们的实际需求究竟是什么?....
产品经理推了推眼镜:“我们要在日志的后台管理界面加一个功能,可以通过作者名称搜索到相应的文章。这个比较急,今晚就要完成。”
保持淡定,需求变更是常态。忽略进度要求,先研究具体实施步骤。
其实很简单,即在 POST 的 admin 界面增加一列作者名称,并通过作者名的模糊搜索找到对应日志。若通过作者 id 搜索固然简单,但用户体验不佳;若仅展示作者名字,添加 header 并将 value 设为 $data->author->username 即可,但这样只能展示,无法进行搜索...令人苦恼。
别急,不就是增加搜索功能吗?下面介绍具体做法。
首先,进入 POST 的 model,在文件开头添加一个新属性。
<pre class="brush:php;"><code class="language-php">
class Post extends CActiveRecord
{
public $name; //添加一个 public 属性,代表作者名
然后改一下 Model 里面 search 的代码,改动部分都已经加了注释:
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->with = array('author'); //添加了和 author 的渴求式加载
$criteria->compare('post_id',$this->post_id);
$criteria->compare('title',$this->title,true);
$criteria->compare('content',$this->content,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('status',$this->status);
$criteria->compare('create_time',$this->create_time);
$criteria->compare('update_time',$this->update_time);
$criteria->compare('author_id',$this->author_id);
//这里添加了一个 compare, username 是 User 表的字段,$this->name 是我们添加的属性,true 为模糊搜索
$criteria->compare('username',$this->name,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
</code></pre>
然后在 view 文件中,即 post 文件夹下的 admin.php,将 CGridView 修改为如下代码。
<pre class="brush:php;"><code class="language-php">
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'post-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'post_id',
'title',
'content',
'tags',
'status',
'create_time',
'update_time',
'author_id',
/*下面就是添加的代码啊*/
array(
'name'=>'作者名称',
'value'=>'$data->author->username', //定义展示的 value 值
'filter'=>CHtml::activeTextField($model,'name'), //添加搜索 filter
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
可能发现现在有了搜索框却无法起作用?哈哈,所以建议文章坚持看到最后。最后一步,是在 rule 中将 name 属性加入安全搜索字段列表中,否则会被 Yii 视为不安全字段而过滤掉。见下方函数最后一行,safe 数组前增加了 name ....
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, content, status, author_id', 'required'),
array('status, create_time, update_time, author_id', 'numerical', 'integerOnly'=>true),
array('title', 'length', 'max'=>128),
array('tags', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('post_id, title, content, tags, status, create_time, update_time, author_id, name', 'safe', 'on'=>'search'),
);
}