by prettyscripts on 2010-09-02 15:31:02
most data have created_date, created_by, updated_date and updated_by columns to audit records. in yii, these columns can be automatically updated via these 2 behaviors:
edit /path/to/models/<Model>.php and add / edit behavior function:
PHP:
public function behaviors() | |
{ | |
return array( | |
'CTimestampBehavior' => array( | |
'class' => 'zii.behaviors.CTimestampBehavior', | |
'createAttribute' => 'created_date', | |
'updateAttribute' => 'modified_date', | |
'setUpdateOnCreate' => true, | |
), | |
'BlameableBehavior' => array( | |
'class' => 'application.components.behaviors.BlameableBehavior', | |
'createdByColumn' => 'created_by', // optional | |
'updatedByColumn' => 'modified_by', // optional | |
), | |
); | |
} |
lines 6, 7: set to null if column does not exist.
line 8: update date column by default is not updated on create unless this is set to true
lines 12, 13: these are not required if the column names are 'created_by', 'modified_by'. it seems to be able to detect such column does not exist too.
now, these fields are automatically updated!
updatedByColumn will not be updated to current user if the field has a value, ie if it is not empty.
if you want this field to always gets updated with every data modification, go to the source code, remove the empty function checking from lines 31 and 34.
add the following attribute somewhere after defining $updatedByColumn:
PHP:
public $userAttribute = 'id'; |
find following codes:
PHP:
$this->owner->{$this->createdByColumn} = Yii::app()->user->id; | |
$this->owner->{$this->updatedByColumn} = Yii::app()->user->id; |
replace 'id' with {$this->userAttribute}, so the code looks like:
PHP:
$this->owner->{$this->createdByColumn} = Yii::app()->user->{$this->userAttribute}; | |
$this->owner->{$this->updatedByColumn} = Yii::app()->user->{$this->userAttribute}; |
edit /path/to/models/<Model>.php and add / edit behavior function to set userAttribute:
PHP:
Tags: behavior, created, extension, modified, timestamp, updated, yii