Question About Model Variable

Hi Yii Community,

I’m a newbie at Yii and I have come across the following question:

On admin.php created by Gii, it uses the CGridView widget, which helps a lot. As I have a relation in my database, I want to show one of the fields using the relation. For example:

Table: State

Fields: id, name

Table: City

Fields: id, name, state_id

state_id is a foreign key to State table, field id

I want the admin.php on city view to show state->name instead of city->state_id.

To do that, I have searched this forum and I came across the answer:

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

'id'=&gt;'city-grid',


'dataProvider'=&gt;&#036;model-&gt;search(),


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


'columns'=&gt;array(


	'id',


	'name',


	array(


                'name'=&gt;'state_id',


                'filter'=&gt;CHtml::listData(State::model()-&gt;findAll(), 'id', 'name'),


                'value'=&gt;'State::Model()-&gt;FindByPk(&#036;data-&gt;state_id)-&gt;name',


            ),


	array(


		'class'=&gt;'CButtonColumn',


	),


),

)); ?>

This worked perfectly, and changed the search field for State to a select form field, which is perfect. But, I still have a question:

On the header, it shows:

/* @var $this CityController */

/* @var $model City */

Which makes me think that instead of $data->state_id, I should have used $model->state_id. To my surprise, when I change to $model, it didn’t work.

On the other hand, when I edited the City view file view.php, I also want it to show the State name instead of state_id, looking at the headers:

/* @var $this CidadeController */

/* @var $model Cidade */

So I changed the CDetailView to:

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

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


'attributes'=&gt;array(


	'id',


	'name',


	array(


                'name'=&gt;'state_id',


                'value'=&gt;CHtml::encode(&#036;model-&gt;state-&gt;name),


            ),


),

)); ?>

And it worked! I tried just for curiosity using $data->state->name and it didn’t work.

The question is: when to use $data and when to use $model?

Also, just a curious fact, on CDetailView, if I use ‘value’=>’$model->state->name’, it considers $model->state->name to be a string. On CGridView it is ok to use it. Any explanation to this?

Thanks in advance and I’m sorry if this seems to be such a newbie question, but it is really messing my thoughts.,

Eugenio Pacheco

In your CityController has index, create, view … actions, right?

$model is variable wich is coming from your controller.




   $this->render('update',array(

	'model'=>$model,

   ));



I highly recommend you that you have to read Larry Ullman - The Yii Book (2013)

I second the suggestion to get a copy of the Larry Ullman book.

It is reasonably priced, very well written and covers a lot of useful subjects in great detail – including the one you were wondering about.

It is more than 500 pages now, and still growing.