AuditBehavior class

If you’re worried about who made changes and when they were made this class will help. Attach it to a CActiveRecord model an define the fields in your database model (updated_by_id, updated_at, created_by_id, created_at). I had to define them as nullable so that they did not trigger validation rules. That’s fine since they are automatically generated by this class, so no data integrity issues. I haven’t got around to defining the ‘deleted_by’ auditing yet; that’s a much bigger task that requires filtering all views of the data by a ‘deleted’ flag.




class AuditBehavior extends CActiveRecordBehavior

{

  public function beforeSave($event)

  {

    $user_id = Yii::app()->user->getId();

    $now = new CDbExpression('NOW()');


    if($this->Owner->isNewRecord) {

      $this->Owner->created_by_id = $user_id;

      $this->Owner->created_at = $now;

    }


    $this->Owner->updated_by_id = $user_id;

    $this->Owner->updated_at = $now;


    return parent::beforeSave($event);

  }

}