TimeStampBehavior example

I have two fields, dateCreated, dateChanged. They are both timestamp fields. I want to use the TimeStampBehavior in the controller to fill these fields automatically. I’ve placed this code in the controller:


public function behaviors(){

	return array(

		'CTimestampBehavior' => array(

			'class' => 'zii.behaviors.CTimestampBehavior',

			'createAttribute' => 'create_time_attribute',

			'updateAttribute' => 'update_time_attribute',

		)

	);

}

I’ve not been successful in having the two fields filled automatically. :angry: Any help will be appreciated.

Explained here:

http://www.yiiframework.com/doc/api/CTimestampBehavior

You have to create the behavior() method in your model.

/Tommy

Yeah, I’ve tried that. I’ve used the same code in my model with no success.

The createAttribute and updateAttribute you have to set to your fields like:




public function behaviors(){

   return array(

      'CTimestampbehavior' => array(

         'class' => 'zii.behaviors.CTimestampbehavior',

         'createAttribute' => 'dateCreated',

         'updateAttribute' => 'dateChanged',

      )

   );

}



note that "B" in "behavior" in CTimestampBehavior should be "Behavior"… this forum converts it to lower letter

Works like a charm :) Can’t thank you enough!

Hi Maurizio,

I would like to ask about this behavior. I set the timezone in the index.php file in my yii project. Unfortunately this TimestampBehavior does not take care this timezone setting. How can i set the timezone in the behavior ?

Thanks

Laszlo from Hungary

if you check the source code you will see that this behavior sets the value of the fields to CDbExpression(‘NOW()’)… so it’s the database (not the PHP script) that sets the date…

oops i should have check that

thanks anyway, have a nice day!

if it just would be useful for someone, i solved my problem:

You have to set an attribute when calling the behavior and the timestamp is set by php now:


'CTimestampBehavior' => array(

                'class' => 'zii.behaviors.CTimestampBehavior',

                'createAttribute' => 'created',

                'updateAttribute' => 'modified',

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

                'setUpdateOnCreate' => true,

            ),