Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get related values in Yii?

Tags:

php

yii

Schema:

CITY
ID (int)
Name (string)
Status (int)

CITY_STATUS
ID (int)
Name (string)
  1. 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

  2. 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?

like image 323
Neil McGuigan Avatar asked Feb 26 '23 18:02

Neil McGuigan


1 Answers

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.

like image 169
Neil McGuigan Avatar answered Mar 09 '23 06:03

Neil McGuigan