2012-12-19 55 views
1

我會將用戶的生日分爲三種不同的字段:日,月和年。 我想知道我是否做得對,並且如果有更簡單的方法來做到這一點。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 DD/MM/YYYY到SQL表的格式,最有可能像YYYY-MM-DD轉換),那麼你可以在保存模型之前進行轉換,就像這樣;

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

嗨Stu。關於使用函數getBirthday,在創建表單時應該如何? '<?php echo CHtml :: activeTextField($ model,'???')?>'在表單輸入之後,我如何獲取條目? –

+0

使用CJuiDatePicker,你能給我一個更新動作的例子嗎?因爲它必須從數據庫載入新生代數據庫,這是形成Y-m-d。 –

+0

嗨,我編輯了應該是一個更完整的例子的答案,我沒有測試它,所以要警告,它可能需要一點編輯!將模型參數添加到小部件應自動轉換日期格式並將其添加到更新表單中的文本字段中。 – Stu