0

使用后$model->save();取消现有行为DateTimeI18NBehavior。有谁知道怎么解决?

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


用户.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

1 回答 1

3

那是DateTimeI18NBehavior. 它在保存数据之前将日期时间格式化为 Ymd 并保持原样。一个快速的解决方法是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;
    }
于 2013-02-21T10:00:57.963 回答