AutoTimestampBehavior

2 2
3
Viewed: 28 613 times
Version: Unknown (update)
Category: Tutorials
    Written by: jonah jonah
    Updated by: Yang He Yang He
    Created: Feb 19, 2009
    Updated: 14 years ago

    You are viewing revision #1 of this wiki article.
    This version may not be up to date with the latest version.
    You may want to view the differences to the latest version.

    next (#2) »

    This behavior will automatically set timestamp fields to the row creation and modification times.

    <?php
    class AutoTimestampBehavior extends CActiveRecordBehavior {
    
    	/**
    	* The field that stores the creation time
    	*/
    	public $created = 'created';
    	/**
    	* The field that stores the modification time
    	*/
    	public $modified = 'modified';
    	
    	
    	public function beforeValidate($on) {
    		if ($this->Owner->isNewRecord)
    			$this->Owner->{$this->created} = new CDbExpression('NOW()');
    		else
    			$this->Owner->{$this->modified} = new CDbExpression('NOW()');
    			
    		return true;	
    	}
    }
    
    Installing to a model ΒΆ

    Drop the following into your model to install it:

    public function behaviors(){
    	return array(
    		'AutoTimestampBehavior' => array(
    			'class' => 'application.components.AutoTimestampBehavior',
    			//You can optionally set the field name options here
    		)
    	);
    }