Time Stamp location model or controller

Hello,

I am trying to have the created_at and updated_at timestamp to add itself in my tables but I am not sure if I should put the below code in the controller or the model, anyone please?




use yii\db\Expression;

use yii\behaviors\TimestampBehavior;

public function behaviors()

{

    return [

        [

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

            'createdAtAttribute' => 'created_at',

            'updatedAtAttribute' => 'updated_at',

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

        ],

    ];

}



Thank you,

Ben

So here is what I did, I have setup the code in the controller as it is seems logical to do it here due to the behaviors being already there.

But in the database, the dates safe as "null" on both the created_at and updated_at.

I have also set both database fields to "DATETIME(6)".

Here is the controler code:




<?php


namespace frontend\controllers;


use Yii;

use frontend\models\Categories;

use frontend\models\CategoriesSearch;

use yii\web\Controller;

use yii\web\NotFoundHttpException;

use yii\filters\VerbFilter;

use yii\db\Expression;

use yii\behaviors\TimestampBehavior;


/**

 * CategoriesController implements the CRUD actions for Categories model.

 */

class CategoriesController extends Controller

{

    public function behaviors()

    {

        return [

            'verbs' => [

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

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

            

            [

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

            'createdAtAttribute' => 'create_time',

            'updatedAtAttribute' => 'update_time',

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

            ],

            

            

        ];

    }


    /**

     * Lists all Categories models.

     * @return mixed

     */

    public function actionIndex()

    {

        $searchModel = new CategoriesSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }


    /**

     * Displays a single Categories model.

     * @param integer $id

     * @return mixed

     */

    public function actionView($id)

    {

        return $this->render('view', [

            'model' => $this->findModel($id),

        ]);

    }


    /**

     * Creates a new Categories model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new Categories();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Updates an existing Categories model.

     * If update is successful, the browser will be redirected to the 'view' page.

     * @param integer $id

     * @return mixed

     */

    public function actionUpdate($id)

    {

        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('update', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Deletes an existing Categories model.

     * If deletion is successful, the browser will be redirected to the 'index' page.

     * @param integer $id

     * @return mixed

     */

    public function actionDelete($id)

    {

        $this->findModel($id)->delete();


        return $this->redirect(['index']);

    }


    /**

     * Finds the Categories model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return Categories the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = Categories::findOne($id)) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}




Thank you,

Ben

I then tried this code, still no luck, both fields are showing "not set in the view and "null" in the database, but at least I have no errors while saving:




<?php


namespace frontend\controllers;


use Yii;

use frontend\models\Categories;

use frontend\models\CategoriesSearch;

use yii\web\Controller;

use yii\web\NotFoundHttpException;

use yii\filters\VerbFilter;

use yii\db\ActiveRecord;

use yii\db\Expression;




/**

 * CategoriesController implements the CRUD actions for Categories model.

 */

class CategoriesController extends Controller

{

    public function behaviors()

    {

        return [

            'verbs' => [

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

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

            

            'timestamp' => [

                'class' => 'yii\behaviors\TimestampBehavior',

                'attributes' => [

                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],

                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],

                ],

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

            ],     

        ];

    }


    /**

     * Lists all Categories models.

     * @return mixed

     */

    public function actionIndex()

    {

        $searchModel = new CategoriesSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }


    /**

     * Displays a single Categories model.

     * @param integer $id

     * @return mixed

     */

    public function actionView($id)

    {

        return $this->render('view', [

            'model' => $this->findModel($id),

        ]);

    }


    /**

     * Creates a new Categories model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new Categories();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Updates an existing Categories model.

     * If update is successful, the browser will be redirected to the 'view' page.

     * @param integer $id

     * @return mixed

     */

    public function actionUpdate($id)

    {

        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('update', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Deletes an existing Categories model.

     * If deletion is successful, the browser will be redirected to the 'index' page.

     * @param integer $id

     * @return mixed

     */

    public function actionDelete($id)

    {

        $this->findModel($id)->delete();


        return $this->redirect(['index']);

    }


    /**

     * Finds the Categories model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return Categories the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = Categories::findOne($id)) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}




Model handles the data.

So you have to attach the TimeStamp behaviour at the model. ;)

http://www.yiiframework.com/doc-2.0/guide-concept-behaviors.html

Put in your model for example:




use yii\behaviors\TimestampBehavior;


public function behaviors()

{

  // when your fields are named "created_at" and 

  // "updated_at" and you want the unix timestamp 

  // you dont need the settings I commented out.

  return [

		[

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

			// 'createdAtAttribute' => 'create_time',

			// 'updatedAtAttribute' => 'update_time',

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

		],

	];

}



Regards

Thank you.

I have also tried that but still get "null" in both database column for the created_at and updated_at.

How do you normally set the fields in mysql please

Is DATETIME(6) correct?

Is there anything else anywhere I should set?

Thank you,

Ben

There is your problem DATETIME(6) is incorrect.

If you are working with unix timestamps that should be:

or if you working with migrations:




$this->createTable('my_tablename', array(

		// ... other attributes ...

		'created_at'	=>	Schema::TYPE_INTEGER . ' NOT NULL',

		'updated_at'	=>	Schema::TYPE_INTEGER . ' NOT NULL',

	), 'ENGINE=InnoDB DEFAULT CHARSET=utf8'

);



But of course it is also possible to work with datetime.

You just have to modify the "value" attribute of the bahvior to generate a mySQL Datetime.

For Example (with mySQL Datetime):




public function behaviors()

{

    return [

        [

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

            //'createdAtAttribute' => 'created_at',

            //'updatedAtAttribute' => 'updated_at',

            'value' => date("Y-m-d H:i:s"), 

        ],

    ];

}



But remember that DATETIME and TIMESTAMP values have both their advantages and disadvantages.

Just google after “DATETIME vs TIMESTAMP” and read several articles… ;)

Regards

Thank you for your help.

I tied your code but could not get it to work.

Instead I used this which worked great:

public function behaviors()

{

return [


    [


        'class' =&gt; TimestampBehavior::className(),


        'createdAtAttribute' =&gt; 'created_at',


        'updatedAtAttribute' =&gt; 'updated_at',


        'value' =&gt; new Expression('NOW()'),


    ],


];

}

Just one tiny problem I am getting in the index view too many zeros for the time.

2015-04-24 21:17:07.000000

I have no idea why this is happening…