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:
Fields: id, name
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'=>'city-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( 'id', 'name', array( 'name'=>'state_id', 'filter'=>CHtml::listData(State::model()->findAll(), 'id', 'name'), 'value'=>'State::Model()->FindByPk($data->state_id)->name', ), array( 'class'=>'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'=>$model, 'attributes'=>array( 'id', 'name', array( 'name'=>'state_id', 'value'=>CHtml::encode($model->state->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.,