Yii: 如何在CGridView组件中根据不同的记录行数据显示不同的操作

来源:互联网 发布:连云港网络推广 编辑:程序博客网 时间:2024/04/30 22:48

使用CGridView来显示表格数据,一个简单的需求如下:

表格中显示文章,每行的操作列需要根据文章的状态而变化,

比如已审核的文章不需要出现审核的操作,而处于新建状态的文章可以有批准和拒绝的动作。


缺省情况下CGridView是无法实现以上需求的,其CButtonColumn中的template虽然可以定制,但对每一行数据都一样。

'columns'=>array(...array(    'class'=>'FButtonColumn',  'header'=>'Actions',    'template'=>'{view} {approve} {reject}',            'buttons'=>array(                'view'=>array(                    'label'=>'View',                    'url'=>'Yii::app()->controller->createUrl("view", array("Id"=>$data->primaryKey))',                ),                'approve'=>array(                'label'=>'Approve',                               'url'=>'Yii::app()->controller->createUrl("approve", array("Id"=>$data->primaryKey))',                ),                'reject'=>array(                'label'=>'Reject',                'url'=>'Yii::app()->controller->createUrl("reject", array("Id"=>$data->primaryKey))',                ),                          ),  'htmlOptions'=>array('class'=>'alignLeft'),)...)   

解决方法:

从CButtonColumn派生一个类FButtonColumn,override其init和renderDataCellContent方法:

    public function init()    {$this->initDefaultButtons();foreach($this->buttons as $id=>$button) {if(strpos($this->template,'{'.$id.'}')===false &&$this->template != '$data->getTemplate()')unset($this->buttons[$id]);...}    ...    }    protected function renderDataCellContent($row,$data)    {        $tr=array();        ob_start();        foreach($this->buttons as $id=>$button)        {            $this->renderButton($id,$button,$row,$data);            $tr['{'.$id.'}']=ob_get_contents();            ob_clean();        }        ob_end_clean();        if($this->template === '$data->getTemplate()') {            $template = $this->evaluateExpression($this->template,array('row'=>$row,'data'=>$data));        }        echo strtr($template,$tr);    } 

然后更改视图中的template参数如下:

'template'=>'$data->getTemplate()',


iefreer