Display name instead id in view

Hello,

probably a very newbish question, but I’ve literally just started using Yii and frameworks in general and am a bit lost.

Basically let’s say I have Country table (id, name) and city table (id, country_id, name). I made city.country_id associate with country.id via FK comment thing.

Now, when I load up city view right now it shows:

Id - …

Country_id - …

Name - …

What I want is to change country_id into country.name

How is the best way to do that?

Thanks in advance!

if your city has a relation country (BELONGS_TO), then:




$model = City::model()->findByPk($cityId);

echo $model->country->name;



http://www.yiiframework.com/doc/guide/database.arr

Not exactly the solution I was looking for, but it pointed me in the right direction, thanks!

In case anybody else will be in my boat, what you will need to do is edit view.php in view/modelname/view.php


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

	'data'=>$model,

	'attributes'=>array(

                'id',

		'name',

                'country_id')); ?>



into


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

	'data'=>$model,

	'attributes'=>array(

                'id',

		'name',

                 array(

                    'label' => $model->country->getAttributeLabel('country'),

                    'value' => $model->country->name

                ),)); ?>



hi

but when i try this it says country.country is not defined

That is because you don’t have a relation named country in your model class. Either define a relation in relations method or change country to whatever is the name of your relation.

Hi,

You need to set relation in model.php

return array(

	'country'=&gt;array(self::BELONGS_TO, 'Country', 'country_id'),


	);

Now in admin.php

array(

              'name' =&gt; 'country_id',


               'header'=&gt;'Counrty Name',


                'value' =&gt; '&#036;data-&gt;country-&gt;name'


            ),

Hi newbie,

------ in your model -------

you always have a public function that contains all the relations

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(


		'idCounty' =&gt; array(self::BELONGS_TO, 'name_of_your_model that you are going to use', 'id_country'),


		


	);


}

-----in your index view ---------

note: i use yii booster but, the function is very similar

<?php $this->widget(‘booster.widgets.TbDetailView’, array(

'data'=&gt;&#036;model,


'attributes'=&gt;array(


	


	array ('name'=&gt;'id_contry', 


		'value'=&gt;&#036;model-&gt;idCounty-&gt;name of the column you need to display,


		'type'=&gt;'text',


		),


	


),

)); ?>

hope solve your problem with this solution

You have truly been an inspiration.