Schema:
CITY
ID (int)
Name (string)
Status (int)
CITY_STATUS
ID (int)
Name (string)
When I display a city (in the View view), I want to display the related CITY_STATUS.Name value, instead of the CITY.Status value
When I add or update a city, I want to display a drop down of all CITY_STATUS.Names in the drop down
How do I do this in Yii?
Guess I'll answer it myself.
Question 1
Relations are easier if you setup a foreign key in your database first. To do this you need to use MySQL (not SQLite) with the InnoDB engine (not MyISAM), and the field in question needs an index on it. Then, Gii will setup the relations function for you automatically. Otherwise, you'll have to do it manually in the relations() function of the model in question.
To use a related value in a View:
In protected/views/[model name]/view.php, in the CDetailView attributes array, change
'Status'
to
array('label'=>'Status', 'value'=>$model->RelationName->Name)
where RelationName is the name of the relation
To use a related value in an Index view, change protected/views/[model name]/_view.php (note the underscore), for example in this case you would change
$data->Status
to
$data->RelationName->Name
To use a related value in an Admin view, in the CGridView widget call, in the columns array, replace say
'Status'
with
array('name'=>'Status', 'header'=>'Status', 'value'=>'$data->RelationName->Name')
(note the use of the variable $data, and not say $model or $dataProvider). Still trying to figure out how to sort and filter...
Question 2
To use a drop-down menu, in protected/views/[model name]/_form.php:
change
<?php echo $form->textField($model,'Status'); ?>
to
<?php echo $form->dropDownList($model,'Status', CHtml::listData(Status::model()->findAll(), 'ID', 'Name')); ?>
el chief, you are a gentleman and a scholar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With