2013-03-05 138 views
3

我有這樣一個數組:
日期的格式無效

$holiday = array(array('h_date' => $new_year, 'd_name' => 'New Year'), 
    array('h_date' => $memorial_day, 'd_name' => 'Memorial Day') 
foreach($holiday as $holidays){ 
$date = $holidays["h_date"]; 
$name = $holidays["d_name"] 


當我保存在MySQL數據庫

$model = new Holiday(); 
$model->holiday_date = $date; 
$model->display_name = $name; 
$model->save(); 

當我寫

$model->save(false); 


值保存成功,但看到比錯誤驗證錯誤時沒有 「假」 數據不保存

Array ([holiday_date] => Array ([0] => The format of Holiday Date is invalid.)) 


我們使用

protected function beforeSave(){ 
    if(parent::beforeSave()){ 
     $this->holiday_date=date('Y-m-d',strtotime($this->holiday_date)); 

     return TRUE; 
    } 

    return false; 
} 
+1

您節省的領域是char更改爲date – Vineet1982 2013-03-05 05:45:35

+0

先生,請詳細說明。 – Rishabh 2013-03-05 05:53:09

+0

在mysql中將字段類型從char轉換爲日期 – Vineet1982 2013-03-05 05:53:52

回答

1

您應該更改日期格式on beforeValidate或者更改holiday_date屬性的驗證規則,因爲在驗證通過後執行beforeSave。

public function beforeValidate() 
{ 
    if ($this->isNewRecord) 
    { 
     $this->holiday_date = date('Y-m-d', strtotime($this->holiday_date)); 
    } 
    return parent::beforeValidate(); 
} 
+0

感謝您的回答。當我在驗證規則日期格式cahnge保存,但在這種情況下沒有保存的數據 – Rishabh 2013-03-06 06:18:45

+0

你可以發佈你的模型的驗證規則? – Puigcerber 2013-03-06 10:00:39

+0

是的,我們可以在Yii框架中創建自己的驗證規則.http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/ – Rishabh 2013-03-06 10:50:27