缺省情况下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()',
示例代码:
model
public function allBranchs() { $criteria = new CDbCriteria; $criteria->with = 'parent'; return new CActiveDataProvider($this, array( 'criteria' => $criteria, )); }
view
$this->widget('zii.widgets.grid.CGridView', array( 'dataProvider' => $model->allBranchs(), 'pager' => array( 'maxButtonCount' => '7', ), 'template' => '{pager}{summary}{items}{pager}', 'columns' => array( array( 'class' => 'CCheckBoxColumn', 'selectableRows'=>2, 'value' => $model->id, ), 'id', 'parent_id', array( 'header' => 'Parent Name', 'name' => 'parent.name', ), 'path', 'name', 'description', 'uid', array( 'class'=> 'CButtonColumn', 'header' =>'操作', 'deleteConfirmation' => '确定删除?', ), ) ));