I've already spent many of hours, but I can't figure it out what is the problem yet.
I'm trying to implement a TimeStampBehaviour
(and Blamable
, but neither of them are working now). My model class:
<?php
namespace common\models;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
/**
* This is the model class for table "news".
* .... property list
*/
class News extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'news';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'short_description', 'content'], 'required'],
[['content'], 'string'],
[['title'], 'string', 'max' => 128],
[['short_description'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
// ... attribute label list
}
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
'value' => new Expression('NOW()'),
],
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
];
}
}
I can save my model, every field is updated correctly, but the created_at
, updated_at
, created_by
, updated_by
fields are always empty.
My database table name is news, and it contains the 4 field: created_at
and updated_at
field's type is DATETIME (I've already tried with INT and UNIX timestamp, but it doesn't work), and the other ones type is INTEGER.
What could be the problem ? I've tried everything I've found with my friend, Google. :) Thanks.
Update #1:
My NewsController's create and update actions:
public function actionCreate()
{
$model = new News;
if ($model->load(Yii::$app->request->post()))
{
if($model->save()) {
$this->redirect(array('index'));
}
}
return $this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate($id)
{
$model = $this -> findModel ($id);
if ($model->load(Yii::$app->request->post())) {
if($model->save()) {
$this->redirect(array('index'));
}
}
return $this->render('update',array(
'model'=>$model,
));
}
Update #2: I've 'accidentally' noticed, that the problem is exists if I try to update my model. I've just created a new model, and all of the four column is filled with the correct data.
Update #3:
protected function findModel($id)
{
if (($model = News::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Make sure you are actually changing anything in your model's fields because if you are just clicking "save" button without any change, model is not updated in the database (there is no need to) and because of that TimestampBehavior does not work.