Yii2 TimeStamp Behavior

Okay, sooo, i always like to know when my records are created and when they are updated. ROR provides this by default for example, by updating the created_at and updated_at field.

So i have very many model classes,so i created an AppModel.php and made all the other model classes extend it…and then defined


use yii\behaviors\TimestampBehavior;


public function behaviors()

{

    return [

        TimestampBehavior::className(),

    ];

}

This seemed to work fine, but it sets the updated_at and created_at as 0000-00-00 00:00:00

So i went ahead and changed it to


<?php


namespace frontend\models;


use Yii;

use yii\behaviors\TimestampBehavior;

use yii\db\Expression;

/*All Models are going to extend this class

  It has the behaviors method,which will be used for the created_at and updated_at

  Trying to emphasize DRY(Don't Repeat Yourself)	

*/

 class AppModel extends \yii\db\ActiveRecord

 {

 	public function behaviors()

 	{

 		return [

 			'class' => TimestampBehavior::className(),

 			'value' => new Expression('NOW()') 			

 		];

 	}


 }

Which when i created the first record, it worked fine.

Now when i try to access all my records, i get an error, like in the attachment

Then it goes ahead to complain about the search model class, like in the second attachment.

What am i missing?

After doing more research, turns out… i needed this


 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()'),

            ],           

        ];

     }

Sooo…there is this link to the api, which suggested the first approach, which failed…

The one which worked is this one from the guide.

The problem in you second block of code was that you omitted one level of array (square brackets). This should work:


public function behaviors()

{

    return [

        [

            'class' => TimestampBehavior::className(),

            'value' => new Expression('NOW()'),

        ],

    ];

}