Hi.
How can I get the original value or the attribute in the child class of AttributeBehavior? Is it possible?
I have a model, which has the user_id attribute:
$model->attributes = [
'user_id' => $user->id,
'county_id' => $faker->numberBetween(1, 20),
'type' => $faker->numberBetween(1,3),
'name' => $faker->firstNameFemale,
'display_name' => $faker->randomElement([null, $faker->firstNameFemale]),
];
$model->save();
And here is my AttributeBehavior class:
class UserBehavior extends AttributeBehavior
{
/**
* @var integer the Id of user
*/
public $userIdAttribute = 'user_id';
/**
* @inheritdoc
*
* In case, when the [[value]] is `null`, the result of the MODEL ID of current user.
* will be used as value.
*/
public $value;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->userIdAttribute],
];
}
}
/**
* @inheritdoc
*
* In case, when the [[value]] is `null`, the result of the User ID of current user.
* will be used as value.
*/
protected function getValue($event)
{
if ($this->value === null) {
return Yii::$app->user->id;
}
return parent::getValue($event);
}
}
But in the getValue method, the $this->value is always null, however I set the value of the user_id, attribute.
Is it possible to reach/get the original value of the user_id attribute?
For me, it seems the Yii does not care about the original value of the current attribute, it is always null, if I use the EVENT_AFTER_INSERT, I will get that the $this->value is null also, after insert too. Interesting.
What does $this->value means here?
I tried this:
protected function getValue($event)
{
var_dump($this->owner->attributes['user_id']); // integer 249
var_dump($this->value); // NULL
if ($this->value === null) {
return Yii::$app->user->id;
}
return parent::getValue($event);
}