PHP的Yii框架的基本使用示例(3)

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, )); }


    然后在 view 里面,就是 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', /*下面就是添加的代码啊*/ 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'), ); }


您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/576ed7bf75ad2ced2d9302688cfd057c.html