Display department name instead of department id

Hi Guys,

I am new to Yii. I have just downloaded and it’s really cool. I have followed the tutorial at http://www.larryullman.com/2009/11/07/creating-models-views-and-controllers-in-yii-2/

I wanted to change department to display name instead of id. Can anyone tell me how to change this please? thanks in advance!


Mark Thien

I am not very sure of you are saying but to change displays, go to the views and use the AR to display whatever you wish.

BTW: welcome to the forum

If you want to change the what should be display then go to views


and check the output of the data there.

Manage it and check the results.

Hi Mark

I am also new to Yii but this community offers a lot of help to people like us.

I think I may help you on this as I too have faced similar problem in very starting.

To display the name instead of department id you may have to create a function in your model like this

public function getDeptName(){


   $deptName ='';

   if(trim($deptId)!="" && trim($deptId)!=NULL){

       $deptNameObj  = Dept::model()->findbypk($dept_Id,'',array('select'=>'strDeptName'));  

       $deptName =  $deptNameObj->strDeptName;


   return $deptNameObj  ;


and in your view you can call it like $model->DeptName

I hope it can be of some help

and if anyone has any better solution then please do reply


I would use your own code with just a few simple corrections! :]

[list=1][]Use code attribute in [] brackets or click second button to the right, when pasting a code, so it will be more readable here.[]I don’t think You have to declare $deptName =’’;[]You don’t have to check if $deptId is an empty string and again if it is NULL. I’m not sure, but I think you don’t have to check it at all - findByPk should handle properly situation when given parameter is NULL.[]Why you are returning deptNameObj instead of department name?[/list]I would change your code into

public function getDeptName()


   	if($deptId != NULL) return Dept::model()->findByPk($this->dept_Id, '', array('select'=>'strDeptName'))->strDeptName;  



Hi guys,

In your <webapp name>\protected\views\employee\_view.php, just change to:

&lt;b&gt;&lt;?php echo CHtml::encode(&#036;data-&gt;getAttributeLabel('departmentId')); ?&gt;:&lt;/b&gt;

&lt;?php echo CHtml::encode(&#036;data-&gt;department-&gt;name); ?&gt;

&lt;br /&gt;

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(

    	'Dep' =&gt; array(self::BELONGS_TO, 'Dep', 'Dep_id'),



<b><?php echo CHtml::encode($data->getAttributeLabel(‘Dep_name’)); ?>:</b>

&lt;?php echo CHtml::encode(&#036;data-&gt;Dep_id-&gt;Dep-&gt;Dep_name); ?&gt;

&lt;br /&gt;

how can change name instance of id