Adding a link to a CDataColumn

Backoffice Grid Views often list information like Posts for a blog while showing at the same time linked information like the User who wrote that post. For more efficiency, it is appropriate that the User is displayed as a link to the User detail page.

CDataColumns allow adding a link by modifying the 'value' property for the column, whicle CLinkColumns are built to create columns with links, but not really associated to data.

In order to make the addition of links as easy as this:

$this->widget('zii.widgets.grid.CGridView', array(
    [...other gridview options...],
    'columns'=>array(
                  array(
                     'name'=>'username',
                     'urlExpression'=>'array("admin/devices/view","id"=>$data->user_id)',
                     'class'=>'YDataLinkColumn',
                  ),
               )
    ));

, I created the following class (already referenced in the example above):

/**
 * YDataLinkColumn extends {@link CDataColumn} to facilitate adding
 * links to data values.
 *
 * This is particularly usefull in the backend to go from one entity
 * to the other.
 *
 * YDataLinkColumn 'joins' the {@link CLinkColumn} and {@link CDataColumn}
 * interfaces.
 */
class YDataLinkColumn extends CDataColumn {

    public $urlExpression;
    public $url="javascript:void(0)";
    public $linkHtmlOptions=array();
    public $imageUrl;

    protected function renderDataCellContent($row, $data) {
        ob_start();
        parent::renderDataCellContent($row, $data);
        $label = ob_get_clean();

        if($this->urlExpression!==null)
            $url=$this->evaluateExpression($this->urlExpression,array('data'=>$data,'row'=>$row));
        else
            $url=$this->url;

        $options=$this->linkHtmlOptions;
        if(is_string($this->imageUrl))
            echo CHtml::link(CHtml::image($this->imageUrl,$label),$url,$options);
        else
            echo CHtml::link($label,$url,$options);
    }
}