Tuesday, September 18, 2012

How to Customize cGridView Data Column

I wanted to display the building information in a cGridView table with a owner that has a foreign key with building ID.  Here is how you can customize cGridView Data column. 

In Controller, you can add a function

protected function gridDataBuildingInfo($data,$raw) {
        // ... generate the output for the column

        // Params:
        // $data ... the current row data  
        // $row ... the row index   
        $model=Building::model()->findByPk($data->building_id);
        return  $model->name;  
    }


/* Another example without the need to connect with the database */
protected function gridSeasonName($data,$row)
        {
            switch ($data->Season) {
                case 1:
                    return "Winter";
                    break;
                case 2:
                    return "Fall";
                    break;
                case 3:
                    return "Summer";
                    break;
                case 4:
                    return "Spring";
                    break;
            }
        }


And in the views/owner/admin.php, 
you can modify CGridView as below:

 $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'owner-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'id',
        'name',
        'phone',
        'email',
        array('name'=>'church_id', 'value'=>array($this,'gridDataBuildingInfo')),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
));  



Here is a link to yiiframework.com wiki about customizing complex data columns in cGridView.

http://www.yiiframework.com/wiki/278/cgridview-render-customized-complex-datacolumns/


No comments: