Created
November 20, 2013 22:48
-
-
Save motin/7572582 to your computer and use it in GitHub Desktop.
Behavior to automate setting the "owned by user" attribute to the currently logged in user id upon creation of a record.
Revive of OwnerBehavior from https://github.com/schmunk42/p3extensions/commit/aa990c986fabd4ab5932ee504b593b230238ccac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "thyseus/owner-behavior", | |
"description": "Behavior to automate setting the \"owned by user\" attribute to the currently logged in user id upon creation of a record.", | |
"authors": [ | |
{ "name": "thyseus", "email": "thyseus@gmail.com" } | |
], | |
"require": { | |
"php": ">=5.2.0" | |
}, | |
"autoload": { | |
"classmap": ["."] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Owner Behavior by thyseus <thyseus@gmail.com> | |
// Assuming a dataset is "owned" by a user, we need to set the id | |
// of the current logged in user when saving the dataset automatically. | |
// Optional, a "last updated by" column can save the user that last updated | |
// the dataset. The Owner will never be touched. | |
class OwnerBehavior extends CActiveRecordBehavior { | |
/** | |
* The field that stores the pk of the owner | |
*/ | |
public $ownerColumn = 'owner_id'; | |
/** | |
* The field that stores the pk of user that did the the last change | |
*/ | |
public $lastChangeColumn = 'last_change_by'; | |
public function beforeValidate($on) { | |
if(isset($this->owner->tableSchema->columns[$this->ownerColumn])) | |
if ($this->owner->isNewRecord) | |
$this->owner->{$this->ownerColumn} = Yii::app()->user->id; | |
return true; | |
} | |
public function beforeSave($on) { | |
if(isset($this->owner->tableSchema->columns[$this->lastChangeColumn])) | |
$this->owner->{$this->lastChangeColumn} = Yii::app()->user->id; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment