2013-03-05 112 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