2012-11-16 1 views
0

:<select>에 (key-> value), 필드에 "key"가있는 모델이 있습니다. "키"대신보기에서 "값"을 어떻게 표시 할 수 있습니까? 모델에서

public function getOptionsGender() 
{ 
    array(0=>'Any', 1=>Male', 2=>'Female'); 
} 

보기에서 (편집) :

echo $form->dropDownList($model, 'gender', $model->optionsGender); 

하지만 난과 CDetailView이 "원시"속성, 대신 성별의 번호를 표시합니다.

$attributes = array(
    ... 
    'gender', 
) 
  1. 성별에 다시이 숫자를 변환하는 적절한 방법은 무엇입니까? $this->gender = getOptionsGender($this->gender)과 같은 필드를 대체하여 모델에서 사용해야합니까? 모든 github 예제는 매우 감사하겠습니다.

  2. 나는이 것과 관련이없는 몇 가지 견해에서 성별, 연령, 도시, 국가 등을 선택해야했습니다. 내 getOptionsGender 함수 정의는 어디에 배치해야합니까? 당신의 도움에 대한


감사는 문제가 해결된다. 모델에서 :

보기에서
public function getGenderOptions() { ... } 

public function genderText($key) 
{ 
    $options = $this->getGenderOptions(); 
    return $options[$key]; 
} 

: 작업 예제는 여기에서 찾을 수 있습니다

$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, 
)); 

: 제프리 Winsett의 책 "YII 1.1과 민첩한 웹 응용 프로그램 개발"에서 https://github.com/cdcchen/e23passport/blob/c64f50f9395185001d8dd60285b0798098049720/protected/controllers/UserController.php

답변

1

, 그는 사용중인 모델의 클래스 상수를 사용하여 문제를 처리합니다. 귀하의 경우 : 여러 모델이 같은 데이터가있는 경우, 당신은 확장하는 기본 모델을 만들 수 있습니다

array(
    'name'=>'gender', 
    'value'=>CHtml::encode($model->genderText()), 
), 

: 당신이 할 것이다 당신의 CDetailView에 그런

class Model extends CActiveRecord 
{ 
    const GENDER_ANY=0; 
    const GENDER_MALE=1; 
    const GENDER_FEMALE=2; 

    public function getGenderOptions(){ 
     return array(
      self::GENDER_ANY=>'Any', 
      self::GENDER_MALE=>'Male', 
      self::GENDER_FEMALE=>'Female', 
     ); 
    } 
    public function getGenderText(){ 
     $genderOptions=$this->genderOptions(); 
     return isset($genderOptions[$this->gender]) ? $genderOptions[$this->gender] : "unkown gender({$this->gender})"; 
    } 
} 

는에 gender에서 변경하기 CActiveRecord를 만들고 CActiveRecord 대신 새 모델을 확장합니다. 이 모델이 해당 데이터를 가진 유일한 모델 (즉, 사용자 모델은 성별을 가지고 있음)이지만 다른 뷰는 해당 모델을 사용하여 데이터를 표시하면 단일 모델 클래스에 남겨 둡니다. 또한 확장 클래스에 getGenderOptions을 배치하고 모든 모델을 확장하면 해당 모델은 모두 해당 옵션을 사용할 수 있지만 필요한 속성이 없을 수 있으며 확인하지 않을 경우 오류가 발생합니다.

이 모든 것이 언급되었지만 여전히 문제 또는 선호라고 생각합니다. 원하는 곳 어디서나 원하는대로 처리 할 수 ​​있습니다. 이것은 내가 Yii에 대해 특별히 가지고있는 책의 한 예입니다.