I am using YII2 advanced application template with yii2-user.
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
This will set the current timestamp value in my user model. But I want to add this only if it's null; it should not be overwritten if I set the value in my controller.
You can create your TimestampBehavior with custom logic:
<?php
namespace app\behaviors;
use yii\db\ActiveRecord;
use yii\base\Behavior;
use yii\db\Expression;
class ARTimestampBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
];
}
public function beforeInsert($event)
{
$model = $event->sender;
if ($model->hasAttribute('created_at') && is_null($model->created_at)) {
$model->created_at = new Expression('NOW()');
}
if ($model->hasAttribute('updated_at')) {
$model->updated_at = new Expression('NOW()');
}
}
public function beforeUpdate($event)
{
$model = $event->sender;
if ($model->hasAttribute('updated_at')) {
$model->updated_at = new Expression('NOW()');
}
}
}
And then use it in your model:
public function behaviors()
{
return [
ARTimestampBehavior::className(),
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With