In model:
public function getOptionsGender()
{
array(0=>'Any', 1=>Male', 2=>'Female');
}
In view (edit):
echo $form->dropDownList($model, 'gender', $model->optionsGender);
but I have a CDetailView with “raw” attributes, and it displays numbers instead of genders.
$attributes = array(
...
'gender',
)
-
What is appropriate way to convert these numbers back to genders? Should I do it in a model, replacing fields such as
$this->gender = getOptionsGender($this->gender)? Any github examples will be very appreciated. -
I had to choose gender, age, city, country etc. in a few views that are not related to this one. Where should I place my
getOptionsGenderfunction definitions?
Thank for your help, the problem is solved.
In model:
public function getGenderOptions() { ... }
public function genderText($key)
{
$options = $this->getGenderOptions();
return $options[$key];
}
In view:
$attributes = array(
array (
'name'=>'gender',
'type'=>'raw',
'value'=>$model->genderText($model->gender), //or $this->genderText(...)
),
);
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>$attributes,
));
The working example can be found here:
https://github.com/cdcchen/e23passport/blob/c64f50f9395185001d8dd60285b0798098049720/protected/controllers/UserController.php
In Jeffery Winsett’s book “Agile Web Application Development with Yii 1.1”, he deals with the issue using class constants in the model you are using. In your case:
Then in your CDetailView you would have to alter it from
genderto:If several models have the same data, you may want to create a base model that extends CActiveRecord and then extend the new model instead of CActiveRecord. If this model is the only one with that data (ie User model only has gender), but other views use that model to display data, then I would leave it just in the single model class. Also keep in mind that if you place
getGenderOptionsin the extended class, and you extend ALL your models, they will all have that option available, but may not have the attributes needed and will throw an error if you aren’t checking for it.All this being said, I still think it is a matter or preference. You can handle it however you want, wherever you want. This is just one example from a book I have specifically on Yii.