Skip to content

Instantly share code, notes, and snippets.

@ykurnia
Created April 30, 2020 11:12
Show Gist options
  • Save ykurnia/ba9fec22659481c1fdda7d0dee7b01b7 to your computer and use it in GitHub Desktop.
Save ykurnia/ba9fec22659481c1fdda7d0dee7b01b7 to your computer and use it in GitHub Desktop.
Turunan dari ActiveRecord di Yii2, dengan tambahan di beforeSave yang otomatis mengisi data terkait update record (modif by, modif time, etc)
<?php
namespace app\models;
use Yii;
/**
* This is the custom model class for tables
* By Yudi K.
*/
class CustomActiveRecord extends \yii\db\ActiveRecord
{
// before save
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$userIdentity = Yii::$app->user->getIdentity();
if ($this->hasAttribute('id_company') && $this->id_company == '') {
$this->id_company = $userIdentity->idOrg;
}
if ($this->hasAttribute('created') && $this->created == '') $this->created = date("Y-m-d H:i:s");
if ($this->hasAttribute('modified')) $this->modified = date("Y-m-d H:i:s");
if ($userIdentity->id != null) {
if ($this->hasAttribute('created_by') && $insert) $this->created_by = $userIdentity->id;
if ($this->hasAttribute('modified_by')) $this->modified_by = $userIdentity->id;
}
return true;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment