2013-02-21 81 views
0

使用$model->save();後,它取消了現有的行爲DateTimeI18NBehavior。任何人都知道如何解決?行爲和保存()衝突

行爲DateTimeI18NBehavior:http://www.yiiframework.com/extension/i18n-datetime-behavior/


Users.php(模型):

... 
public function behaviors() 
{ 
    return array(
     'datetimeI18NBehavior'=>array(
      'class' => 'ext.DateTimeI18NBehavior', 
     ), 
    ); 
} 
... 

代碼:

$criteria = new CDbCriteria; 
$model = Users::model()->findByPk('1'); 
echo $model->birthday; 
// Response: 15/10/1900 (right) 

代碼2:

$criteria = new CDbCriteria; 
$model = Users::model()->findByPk('1'); 

$model->ip = Yii::app()->request->userHostAddress; 
$model->save(); 

echo $model->birthday; 
// Response: 1990-10-15 (wrong) 
+4

那是在'DateTimeI18NBehavior'的錯誤行爲添加afterSave()事件處理程序。它在保存數據之前將日期時間格式設置爲「Y-m-d」,並保持原樣。一個快速解決的辦法是在行爲 – dInGd0nG 2013-02-21 06:45:02

+0

@ dInGd0nG添加'afterSave()'事件處理程序謝謝,我解決了!你可以將你的'Comment'作爲'Answer'發佈,所以我可以接受它。 – 2013-02-21 07:18:13

+0

答覆補充:) – dInGd0nG 2013-02-21 10:02:07

回答

3

這是一個在DateTimeI18NBehavior中的錯誤。它在保存數據之前將日期時間格式設置爲Y-m-d,並保持原樣。一個快速的解決辦法是在其邏輯是一樣的,即afterFind()

public function afterSave($event){ 

     foreach($event->sender->tableSchema->columns as $columnName => $column){ 

      if (($column->dbType != 'date') and ($column->dbType != 'datetime')) continue; 

      if (!strlen($event->sender->$columnName)){ 
       $event->sender->$columnName = null; 
       continue; 
      } 

      if ($column->dbType == 'date'){    
       $event->sender->$columnName = Yii::app()->dateFormatter->formatDateTime(
           CDateTimeParser::parse($event->sender->$columnName, $this->dateIncomeFormat),'medium',null); 
      }else{    
       $event->sender->$columnName = 
        Yii::app()->dateFormatter->formatDateTime(
          CDateTimeParser::parse($event->sender->$columnName, $this->dateTimeIncomeFormat), 
          'medium', 'medium'); 
      } 
     } 
     return true; 
    }