使用$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)
答案 0 :(得分:3)
这是DateTimeI18NBehavior
中的错误。它在保存数据之前将日期时间格式化为Y-m-d并保持原样。快速解决方法是在行为中添加afterSave()
事件处理程序,其逻辑与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;
}