Yii CGridView CButtonColumn – 2/3

How to toggle Label and imageUrl in CButtonColumn according to different data?

eg. There is status of “lock” in CGridView, if the status is locked, the image in button should be set as unlock. if the data status is unlocked, the image must be set to lock image.

Step 1: Create a sub-class of CButtonColumn

Yii::import('zii.widgets.grid.CButtonColumn');

class ExprButtonColumn extends CButtonColumn
{
    protected function renderButton($id, $button, $row, $data)
    {
        if (isset($button['label']) && strpos($button['label'], '$') > -1)
        {
            $button['label']= $this->evaluateExpression($button['label'],array('data'=>$data,'row'=>$row));
        }
        if (isset($button['imageUrl']) && strpos($button['imageUrl'], '$') > -1)
        {
            $button['imageUrl']= $this->evaluateExpression($button['imageUrl'],array('data'=>$data,'row'=>$row));
        }
        parent::renderButton($id, $button, $row, $data);
    }
}

Step 2: use the new sub-class to configure in template

array(
    'class'=>'ExprButtonColumn',
    'template'=>'{view}{lock}',
    'buttons'=>array(
        'view'=>array(
            'label'=>'view project',
            'url'=>'Yii::app()->controller->createUrl("project/view",array("qid"=>$data->id))',
        ),
        'lock'=>array(
            'label'=>'$data->lock_flag == "1" ? "Unlock The Project" : "Lock The Project"',
            'imageUrl'=>'Yii::app()->request->baseUrl."/images/".($data->lock_flag == "1" ? "unlock.gif" : "lock.gif")',
            'url'=>'Yii::app()->controller->createUrl("project/lock",array("qid"=>$data->id))',
        ),
    ),
),

Leave a Reply