Using relations to be viewed in CGridView

guys,pardon…I am still new at this YII-Framework.

i have this issue,

my table is such this :

User = (id, user_name,role_number)

Role = (id,Role_name).

when the data User is listed, I want the role_name to be shown not the ID

the partial of the coding is down below, that i have configured.

user.php =>

public function relations()

{

// NOTE: you may need to adjust the relation name and the related

// class name for the relations automatically generated below.

return array(

‘role_relation’ => array(self::BELONGS_TO, ‘Role’, ‘id’),

);

}

============================================

UserController.php =>

public function actionIndex()

{

$dataProvider=new CActiveDataProvider(‘User’);

$this->render(‘index’,array(

‘dataProvider’=>$dataProvider,

));

}

============================================

index.php =>

$this->widget(‘zii.widgets.grid.CGridView’, array(

‘dataProvider’=>$dataProvider,

‘columns’=>array(

‘id’,

‘user_name’,

‘password’,

array(‘name’=>‘role_number’, ‘header’=>‘Role Name --’,‘value’ =>’$data->role_relation->role_name’ ),

),

));

is there anything I miss from the script above.

please kindly show me to the brighter light guys.

thank You so much…

Did you generate it with Gii? If yes, skip the first part

  1. Im not sure but according to this

The id should be role_number (the FK not the PK. i don’t know if that matters but try).

  1. instead of



array('name'=>'role_number', 'header'=>'Role Name --','value' =>'$data->role_relation->role_name' ),



try


'role_relation.role_name',

If the header is wrong. Change the attributeLabels method in Role model.

P.S use code tags when writing php code. Its really hard to read.

the only mistake seems to be in -


 

return array(

'role_relation' => array(self::BELONGS_TO, 'Role', 'id'),


);



replace ‘id’ with ‘role_number’

like this -




return array(

'role_relation' => array(self::BELONGS_TO, 'Role', 'role_number'),


);



you can customize your zii widget CDetailView as below ,

( I want department name instead of department id )

now i fine department name as $deptInfo passing Department Id ,

$deptName = $model->getDeptNameFromId($model->attributes[‘DEPT_ID’]);

here $deptName gives name of department

now I customize my view as ,


$this->widget('zii.widgets.CDetailView', array(

	'data'=>$model,

	'attributes'=>array(

		'E_NAME',

		'E_EMAIL',

		array('label'=>'Deptpartment Name','value'=>$deptName),   // work as Department Name as lable and takes dynamic value for department

                ..

                ..