Yii : CGridView – Create Custom Column


I have a field which contains one character to represent project status (eg: F=Finished, S=Start, P=Pending, etc)

By default, CGridView will display one character value, but we want CGridView to display its description taken from other table, this is what I did:

First, create a component, let’s name it MyComponent. You can do it by create MyComponent.php and save it in component folder, I write something like this:

<?php
class MyComponent extends CApplicationComponent 
{
 public function getProjectStatus($statusCode)
 { 
 $sql = "SELECT STATUS_CODE,
 DESCRIPTION
 FROM REF_PROJECT_STATUS WHERE STATUS_CODE='$statusCode'";

 $rs = Yii::app()->db->createCommand($sql)->queryAll();

 $data = array();

 foreach($rs as $item){

 $statusCode = $item['STATUS_CODE'];
 $description = $item['DESCRIPTION'];

 $data[$statusCode] = $description;
 }
 
 return $data[$statusCode]; 
 } 
}

This way, you can call the function like this
Yii::app()->mycomponent->getProjectStatus($statusCode)

Then, replace the field name in your views (admin.php) with something like this

array('header' => 'Project Status', 'value' => 'Yii::app()->mycomponent->getProjectStatus($data->PROJECT_STATUS)'),

Some people suggest the function should be static

Yii version: 1.1.10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s