Luciano Nascimento
Luciano Nascimento

Reputation: 2600

Behavior and save() conflict

After using $model->save(); it cancels the existing behavior DateTimeI18NBehavior. Anyone know how to solve?

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


Users.php (model):

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

Code:

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

Code 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)

Upvotes: 0

Views: 146

Answers (1)

dInGd0nG
dInGd0nG

Reputation: 4114

Thats a bug in DateTimeI18NBehavior. It formats the date time to Y-m-d before the data is saved and leave it as it is. A quick fix is to add an afterSave() event handler in the behaviour whose logic is same as that of 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;
    }

Upvotes: 3

Related Questions