如果你只分裂日期分爲三個部分輸入的目的,一個替代的選擇可能是使用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');
......不過還是要去做,這就是最後一位的多個個人喜好!
來源
2012-12-19 14:12:02
Stu
嗨Stu。關於使用函數getBirthday,在創建表單時應該如何? '<?php echo CHtml :: activeTextField($ model,'???')?>'在表單輸入之後,我如何獲取條目? –
使用CJuiDatePicker,你能給我一個更新動作的例子嗎?因爲它必須從數據庫載入新生代數據庫,這是形成Y-m-d。 –
嗨,我編輯了應該是一個更完整的例子的答案,我沒有測試它,所以要警告,它可能需要一點編輯!將模型參數添加到小部件應自動轉換日期格式並將其添加到更新表單中的文本字段中。 – Stu