To use AttributeBehavior, configure the [[attributes]] property which should specify the list of attributes
that need to be updated and the corresponding events that should trigger the update. Then configure the
[[value]] property with a PHP callable whose return value will be used to assign to the current attribute(s).
For example,
php
use yii\behaviors\AttributeBehavior;
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'attribute1',
ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
],
'value' => function ($event) {
return 'some value';
},
],
];
}
Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
not be validated, i.e. they should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
/** * @inheritdoc */ public function behaviors() { return ['timestamp' => ['class' => AttributeBehavior::className(), 'value' => function ($event) { return $this->module->enableConfirmation ? 0 : 1; }, 'attributes' => [self::EVENT_INIT_REGISTER => 'status']], ['class' => TimestampBehavior::className(), 'attributes' => [self::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], self::EVENT_UPDATE => ['updated_at']]], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => ['created_at']], 'value' => function ($event) { $model = $event->sender; return Yii::$app->formatter->asDatetime($model->created_at, 'php:l, j F Y г., H:i:s'); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_VALIDATE => ['created_at']], 'value' => function ($event) { /* @var $model \users\models\Users */ $model = $event->sender; $model->created_at = $model->getOldAttribute('created_at'); return $model->created_at; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => ['updated_at']], 'value' => function ($event) { $model = $event->sender; return Yii::$app->formatter->asDatetime($model->updated_at, 'php:l, j F Y г., H:i:s'); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_VALIDATE => ['updated_at']], 'value' => function ($event) { /* @var $model \users\models\Users */ $model = $event->sender; $model->updated_at = $model->getOldAttribute('updated_at'); return $model->updated_at; }], ['class' => AttributeBehavior::className(), 'attributes' => [self::EVENT_LOGIN => ['auth_key']], 'value' => function ($event) { /* @var $model \users\models\Users */ $model = $event->sender; if (!$model->auth_key && !$model->isNewRecord) { $model->updateAuthKey(); } return $model->auth_key; }]]; }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_AFTER_VALIDATE => [$this->attribute], BaseActiveRecord::EVENT_AFTER_FIND => [$this->attribute]]; } }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => 'date', BaseActiveRecord::EVENT_BEFORE_UPDATE => 'date', BaseActiveRecord::EVENT_AFTER_FIND => 'date']; } }
/** * @inheritdoc */ public function init() { if ($this->attribute !== null) { $this->attributes[BaseActiveRecord::EVENT_BEFORE_INSERT][] = $this->attribute; } parent::init(); }
public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdByAttribute, $this->updatedByAttribute], BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedByAttribute]; } }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => $this->compiledAttribute, BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->compiledAttribute]; } }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->authorAttribute]]; } }
/** * @inheritdoc */ public function behaviors() { return [['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['created_at']]], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'created_ip'], 'value' => function ($event) { return ip2long(Yii::$app->request->getUserIP()); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => 'created_ip'], 'value' => function ($event) { return long2ip($event->sender->created_ip); }], ['class' => BlameableBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'user_id']]]; }
/** * @inheritdoc */ public function behaviors() { return [TimestampBehavior::className(), ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'alias'], 'value' => function ($event) { return Inflector::slug($event->sender->title); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => 'body'], 'value' => function ($event) { return HtmlPurifier::process(Markdown::process($event->sender->content, 'gfm')); }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['cnf_created']], 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['cnf_flags']], 'value' => function ($event) { /** @var Conference $model */ $model = $event->sender; return empty($model->cnf_flags) ? self::CONF_FLAG_DEFAULT : $model->cnf_flags; }]]; }
public function behaviors() { return [['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['route']], 'value' => function ($event) { return Yii::$app->requestedRoute; }], ['class' => BlameableBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['user_id']]], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['ip']], 'value' => function ($event) { return Yii::$app->getRequest()->getUserIP(); }], ['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['datetime']]]]; }
public function init() { parent::init(); if ($this->hashFunction == null) { $this->hashFunction = [$this, 'defaultHashFunction']; } $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => $this->passwordAttribute, BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->passwordAttribute]; $this->value = $this->hashFunction; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'member_id'], 'value' => function ($event) { return Yii::$app->user->identity->id; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'real_amount'], 'value' => function ($event) { return $this->amount - $this->fee; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'status'], 'value' => function ($event) { return 1; }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'createdAtAttribute' => 'created_at', 'updatedAtAttribute' => 'updated_at'], ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'user_id', 'updatedByAttribute' => 'user_id'], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => 'theMust'], 'value' => function ($event) { return $this->kpi->the_must; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => 'theBest'], 'value' => function ($event) { return $this->kpi->the_best; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => 'groupName'], 'value' => function ($event) { return $this->kpi->group->name; }]]; }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->attribute]; } if ($this->attribute === null) { throw new InvalidConfigException('Either "attribute" or "value" property must be specified.'); } }
/** * @inheritdoc */ public function behaviors() { return [TimestampBehavior::className(), ['class' => BlameableBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['user_id']]], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['user_ip']], 'value' => function ($event) { return Yii::$app->getRequest()->getUserIP(); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['user_host']], 'value' => function ($event) { return Yii::$app->getRequest()->getUserHost(); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['user_agent']], 'value' => function ($event) { return Yii::$app->getRequest()->getUserAgent(); }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'member_id'], 'value' => function ($event) { if ($this->member_id) { return $this->member_id; } else { return Yii::$app->user->id; } }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'status'], 'value' => function ($event) { $dw = date("w", strtotime($this->date)); if (in_array($dw, array(0, 6))) { return 1; } else { return 0; } }]]; }
public function behaviors() { // if user is not an admin get the organizer id of the user account // admin users can and must set the organizer_id from a dropdown. if (!\Yii::$app->user->isAdmin()) { return array_merge(parent::behaviors(), [['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'organizer_id'], 'value' => function ($event) { return Yii::$app->user->identity->getOrganizer()->one()->getPrimaryKey(); }]]); } else { return array_merge(parent::behaviors(), []); } }
public function behaviors() { return [['class' => AttributeBehavior::className(), 'attributes' => [self::EVENT_BEFORE_INSERT => [null], self::EVENT_BEFORE_UPDATE => [null]], 'value' => function ($event) { /* @var User $model */ $model = $event->sender; $model->setting = Json::encode($this->settingBuild()); }], ['class' => AttributeBehavior::className(), 'attributes' => [self::EVENT_AFTER_FIND => [null]], 'value' => function ($event) { /* @var User $model */ $model = $event->sender; $model->setAttributes($model->settingParse()); }]]; }
/** * @inheritdoc */ public function init() { parent::init(); if (empty($this->attributes)) { $this->attributes = [$this->trigger => $this->uniqueAttribute]; } if (!empty($this->paramAttributes) && $this->paramOrder === null) { throw new InvalidConfigException('$paramOrder wajib diisi jika $paramAttributes diisi'); } if ($this->length === null) { throw new InvalidConfigException('$length wajib diisi'); } }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'auth_key'], 'value' => function ($event) { return sha1(rand()); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'finance_fund'], 'value' => function ($event) { return $this->investment; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'access_token'], 'value' => function ($event) { return sha1(rand()); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'password_hash'], 'value' => function ($event) { return Yii::$app->security->generatePasswordHash($this->password); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'password_hash2'], 'value' => function ($event) { return Yii::$app->security->generatePasswordHash($this->password2); }]]; }
public function behaviors() { return ['modified' => ['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'modified', ActiveRecord::EVENT_BEFORE_UPDATE => 'modified'], 'value' => function () { return date('Y-m-d H:i:s'); }], 'modifiedGMT' => ['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'modified_gmt', ActiveRecord::EVENT_BEFORE_UPDATE => 'modified_gmt'], 'value' => function () { return gmdate('Y-m-d H:i:s'); }], 'date' => ['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'date', ActiveRecord::EVENT_BEFORE_UPDATE => 'date'], 'value' => function () { return empty($this->date) ? date('Y-m-d H:i:s') : date('Y-m-d H:i:s', strtotime($this->date)); }], 'dateGMT' => ['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'date_gmt', ActiveRecord::EVENT_BEFORE_UPDATE => 'date_gmt'], 'value' => function () { return empty($this->date) ? gmdate('Y-m-d H:i:s') : gmdate('Y-m-d H:i:s', strtotime($this->date)); }], 'slug' => ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'slug', ActiveRecord::EVENT_BEFORE_UPDATE => 'slug'], 'value' => function () { return empty($this->slug) ? $this->genSlug($this->title) : $this->genSlug($this->slug); }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'status'], 'value' => function ($event) { if ($this->status) { return $this->status; } else { return 0; } }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'charge'], 'value' => function ($event) { if ($this->type) { return round($this->total_price * System::loadConfig('sell_fee_rate'), 2); } else { return 0; } }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at']]], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => ['created_at']], 'value' => function ($event) { $model = $event->sender; return Yii::$app->formatter->asDatetime($model->created_at, 'php:l, j F Y г., H:i:s'); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_VALIDATE => ['created_at']], 'value' => function ($event) { $model = $event->sender; $model->created_at = $model->getOldAttribute('created_at'); return $model->created_at; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_AFTER_FIND => ['updated_at']], 'value' => function ($event) { $model = $event->sender; return Yii::$app->formatter->asDatetime($model->updated_at, 'php:l, j F Y г., H:i:s'); }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_VALIDATE => ['updated_at']], 'value' => function ($event) { $model = $event->sender; $model->updated_at = $model->getOldAttribute('updated_at'); return $model->updated_at; }]]; }
public function init() { parent::init(); if (empty($this->attributes)) { foreach ($this->convertAttr as $key => $value) { $attrName = is_scalar($key) ? $key : $value; $convertType = is_scalar($key) ? $value : self::DEFAULT_CONVERT_TYPE; if (!in_array($convertType, $this->allowConvertType)) { throw new \Exception(strtr('Disallow type convert "{type}"', ['{type}' => $convertType])); } $this->attributes[BaseActiveRecord::EVENT_BEFORE_INSERT][] = $attrName; $this->attributes[BaseActiveRecord::EVENT_BEFORE_UPDATE][] = $attrName; $this->attributes[BaseActiveRecord::EVENT_AFTER_FIND][] = $attrName; $this->attributes[BaseActiveRecord::EVENT_AFTER_INSERT][] = $attrName; $this->attributes[BaseActiveRecord::EVENT_AFTER_UPDATE][] = $attrName; } } }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->className == null) { throw new \yii\base\InvalidConfigException("'className' must be set"); } if (!is_array($this->map)) { throw new \yii\base\InvalidConfigException("'map' must be an array; e.g.: ['gid' => 'group_id']"); } else { if (!count($this->map) > 0) { throw new \yii\base\InvalidConfigException("'map' must contain the mapping group => local; e.g.: ['gid' => 'group_id']"); } } if (!Yii::$app instanceof \yii\console\Application) { if (empty($this->attributes)) { $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => array_values($this->map)[0]]; } } }
/** * Evaluates the attribute value and assigns it to the current attributes. If no foreignClass * is specified, it behaves like the normal AttributeBehavior. * @param Event $event */ public function evaluateAttributes($event) { if ($this->foreignClass === null) { parent::evaluateAttributes($event); } elseif (!empty($this->attributes[$event->name])) { $fObjects = $this->getForeignObjects($this->foreignClass[0], $this->foreignClass[1]); $attributes = (array) $this->attributes[$event->name]; $value = $this->getValue($event); $uAttributes = []; $n = count($fObjects); foreach ($attributes as $attribute) { for ($i = 0; $i < $n; ++$i) { $fObjects[$i]->{$attribute} = $value; } $uAttributes[] = $attribute; } foreach ($fObjects as $fObject) { $fObject->save(false, $uAttributes); } } }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['us_created']], 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'password', ActiveRecord::EVENT_BEFORE_UPDATE => 'password'], 'value' => function ($event) { /** @var \yii\base\Event $event */ $model = $event->sender; if (!empty($model->password)) { $model->setPassword($model->password); } return $model->password; }], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'us_confirmkey'], 'value' => function ($event) { /** @var \yii\base\Event $event */ return Yii::$app->security->generateRandomString() . time(); }], ['class' => ActionBehavior::className(), 'allevents' => [ActiveRecord::EVENT_AFTER_INSERT], 'action' => function ($event) { /** @var \yii\base\Event $event */ $model = $event->sender; if ($model->scenario == 'register') { $oNotify = new Notificator([$model], $model, 'confirm_mail'); $oNotify->notifyMail('Подтвердите регистрацию на портале "' . Yii::$app->name . '"'); } }]]; }
public function behaviors() { return [['class' => TimestampBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['prs_created']], 'value' => new Expression('NOW()')], ['class' => AttributeBehavior::className(), 'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => 'prs_confirmkey'], 'value' => function ($event) { /** @var \yii\base\Event $event */ /** @var Person $model */ $model = $event->sender; if ($model->prs_type == Person::PERSON_TYPE_GUEST) { return Yii::$app->security->generateRandomString() . time(); } return $model->prs_confirmkey; }], ['class' => ActionBehavior::className(), 'allevents' => [ActiveRecord::EVENT_AFTER_INSERT], 'action' => function ($event) { /** @var \yii\base\Event $event */ /** @var Person $model */ /** @var \\app\\components\Notificator $oNotify */ $model = $event->sender; if ($model->prs_type == Person::PERSON_TYPE_GUEST) { $oNotify = new Notificator([$model], $model, 'confirm_guest_mail'); $oNotify->sEmailField = 'prs_email'; $oNotify->notifyMail('Подтвердите регистрацию в качестве гостя на портале "' . Yii::$app->name . '"'); } }]]; }