2012-12-19 5 views
1

나는 일, 달 및 년의 3 개의 다른 분야에있는 사용자의 생일을 모양 (보기) 분리 할 것입니다. 제가 제대로하고 있는지, 그리고 이것을 할 수있는 더 쉬운 방법이 있는지 궁금합니다.Yii 일 생일 달 분할 년

더 나은 성능의 방법이 있습니까? 모든 경우에있어서 그것은 필요하지는 않지만 날짜를 분리합니다.


Model.php :

만 입력을 위해 세 부분으로 날짜를 분할하는 경우
public $birthday_day; 
public $birthday_month; 
public $birthday_year; 

... 

public function afterFind() { 
    $this->birthday_day = date('j', strtotime($this->birthday)); 
    $this->birthday_month = date('n', strtotime($this->birthday)); 
    $this->birthday_year = date('Y', strtotime($this->birthday)); 
} 


public function beforeValidate() { 
    if ($this->birthday_day AND $this->birthday_month AND $this->birthday_year) 
     $this->birthday = new DateTime($birthday_year.'-'$birthday_month'-'.$birthday_day); 

} 

답변

1

는 하나 다른 옵션은 사용자가 전체 날짜를 선택할 수 있도록 CJuiDatePicker을 사용할 수 있습니다 예를 들면;

$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'birthday', 
    'model'=>$model, 
    'attribute'=>'birthday', 
    'options'=>array(
     'showAnim'=>'fold', 
    ), 
    'htmlOptions'=>array(
     'style'=>'height:20px;' 
    ), 
)); 

그런 다음 결과를 데이터베이스에 삽입하기위한 원하는 형식으로 포맷 할 수 있습니다.

... 
public function actionCreate() 
{ 
    $model=new Model; 
    if(isset($_POST['Model'])) 
    { 
     $model->attributes=$_POST['Model']; 
     $model->save(); 
     ... 
    } 
    ... 
} 
... 

또는 업데이트; 올바른 형식으로 날짜를 저장하기 위해

... 
public function actionUpdate($id) 
{ 
    $model=$this->loadModel($id); 
    if(isset($_POST['Model'])) 
    { 
     $model->attributes=$_POST['Model']; 
     $model->save(); 
     ... 
    } 
    ... 
} 
... 

(즉, CJuiDatePicker 당신의 SQL 테이블 형식/월/년 dd는 사용자 친화적 인 형식, YYYY-MM-DD와 같은 가장 가능성이 뭔가 변환) 당신은 이렇게하면 모델을 저장하기 전에 이것을 변환 할 수 있습니다. 그런 다음 앱에 다른 표시를위한 특정 일/월/년을해야 할 경우 속성 (public $birthday_day; 등)와 같은 예에서이 같은

public function beforeSave() { 

    $this->birthday=date('Y-m-d',strtotime($this->birthday); // Or however you want to insert it 

    return parent::beforeSave(); 
} 

, 당신은 전혀 그와 아무 잘못을 설정할 수 있습니다 중 . 또는 모델의 인스턴스를 호출 할 때마다 날짜를 변환하지 않으려면 속성을 설정할 수 있습니다.

public function getBirthday($part) { 
    switch($part) 
    { 
     case 'day': 
      return date('j', strtotime($this->birthday)); 
      break; 
     case 'month': 
      return date('n', strtotime($this->birthday)); 
      break; 
     case 'year': 
      return date('Y', strtotime($this->birthday)); 
      break; 
     default: 
      return date('d/m/Y', strtotime($this->birthday)); 
      break; 
    } 
} 

당신이 날 원한다면, 단지 $model->getBirthday('day'); 전화 ... 또는 당신이 그것을하고 싶지 그러나, 마지막 비트의 개인적인 취향!

+0

안녕하세요. 어떻게해야하는지 양식을 만들 때 함수 getBirthday 사용에 관해서? ''폼 입력 후에, 어떻게 항목을 얻습니까? –

+0

CJuiDatePicker를 사용하여 업데이트 동작의 예를 들어 주시겠습니까? 왜냐하면 Y-m-d 형식의 데이터베이스에서 출생을로드해야하기 때문입니다. –

+0

안녕하세요, 더 완벽한 예가되어야하는 답변을 편집했습니다. 테스트하지 않았으므로 경고를 받으십시오. 약간의 편집이 필요할 수 있습니다! 위젯에 모델 매개 변수를 추가하면 날짜 형식이 자동으로 변환되어 업데이트 양식의 텍스트 필드에 추가됩니다. – Stu

관련 문제