Display the name field of the related foreing key in zii.widgets.CDetailView

hi guys, i am trying to to display in the zii.widgets.CDetailView a field of this table that is a foreing key of may users table and display the name.

e.g.

this tabale is the cars

and has the next fields

id_car (PK)

brand

model

id_user (FK)

and in the uers table had the next fields

id_user (PK)

name

pass

so in the view of the cars display

id_car: 287

Brand: Toyota

Model: Tundra

id:user: 847

but i dont k’now how to display

id_car: 287

Brand: Toyota

Model: Tundra

id:user: John Dou

any help will be welcome,

early thanks

If you have already defined a BELONG_TO relation for User in Car, like:




// Car model

	public function relations()

	{

		return array(

			'user' => array(self::BELONGS_TO, 'User', 'user_id'),

		);

	}



Then you can access the user name like this:




// view

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

	'data'=>$model,

	'attributes'=>array(

		'id_car',

		'brand',

		'model',

		array(

			'name' => 'user_id',

			'value' => $model->user->name,

		),

	),

));



Please see "Relational Active Record" section of the tutorial. http://www.yiiframework.com/doc/guide/1.1/en/database.arr

thank you very much… i really am a newbie… :-S thank a lot :slight_smile:

and in the columns of the zii.widgets.grid.CGridView

i try with:


                array(

                        'name' => 'user_id',

                        'value' => $model->user->name,

                ),



but it didn’t work.

any help will be welcome,

early thanks

In a CGridView, use $data instead of $model and enclose the statement in a pair of quotation marks.




                array(

                        'name' => 'user_id',

                        'value' => '$data->user->name',

                ),



See the reference of CGridView. http://www.yiiframework.com/doc/api/1.1/CGridView

You will notice that exactly the same usage of ‘value’ is demonstrated in the example code. :)

And CDataColumn.value http://www.yiiframework.com/doc/api/1.1/CDataColumn/#value-detail

thank you very much softark…

for the record, if the releation doesn’t exist, it doesn’t display anything exept one big error “Trying to get property of non-object”, so if anyone read this i hope this could be a good referens, acheck the information y consist.

thanks softark :slight_smile:

but the search only works with the ID related, it works only with the foreing key???

I will be very glad if some one could help me and guid of how to make that the search field works with entries of the field that we show, in this case the name of the user instead of the Id of the user in the cars admin view of the cars table model.

any help will be welcome,

early thanks.

Have a look at this blog post by MrSoundless:

Searching and sorting a column from a related table in a CGridView

Worked great! Thanks so much.