deleted
deleted
This topic might help you out:
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth
but i believe what you want specifically is:
Yii::app()->user->id
What I do is to create a behavior that updates the fields when I do onSave
Here, one ready to use⦠make sure you change the attributes to suite yours!!!
Yii::import('zii.behaviors.CTimestampBehavior');
class TimestampBehavior extends CTimestampBehavior{
/**
* @var mixed The name of the attribute to store the creator's id. Set to null to not
* use. Defaults to null
*/
public $createdByIdAttribute = null;
/**
* @var mixed The name of the attribute to store the modificator's id. Set to null to not
* use. Defaults to null
*/
public $updateByIdAttribute = null;
public function __construct() {
$this->setUpdateOnCreate = true;
$this->timestampExpression = new CDbExpression('NOW()');
}
/**
* Responds to {@link CModel::onBeforeSave} event.
* Sets the values of the creation or modified attributes as configured
*
* @param CModelEvent $event event parameter
*/
public function beforeSave($event) {
if ($this->getOwner()->getIsNewRecord() && ($this->createAttribute !== null)) {
$this->getOwner()->{$this->createdAttribute} = $this->getTimestampByAttribute($this->createAttribute);
// custom CWebUser will return the id of the logged user
if( $this->createdByIdAttribute !== null && Yii::app()->user->id ){
$this->getOwner()->{$this->createdByIdAttribute} = Yii::app()->user->id;
}
}
if ((!$this->getOwner()->getIsNewRecord() || $this->setUpdateOnCreate) && ($this->updateAttribute !== null)) {
$this->getOwner()->{$this->updateAttribute} = $this->getTimestampByAttribute($this->updateAttribute);
if( $this->updatedByIdAttribute !== null && Yii::app()->user->id ){
$this->getOwner()->{$this->updatedByIdAttribute} = Yii::app()->user->id;
}
}
return parent::beforeSave($event);
}
}
How to use this behavior? http://www.yiiframework.com/doc/api/1.1/CModel#behaviors-detail
// on your model
public function behaviors(){
return array(
'timestamp'=>array('class'=>'TimestampBehavior', // if you dont include this class, put here the alias of the path
'createdByIdAttribute'=>'createbyidfield', // set it to suit your needs
);
}