I have a model with two values that has to be unique together. Yii2 has a validation rule for this:
[['object_id', 'created_by'], 'unique', 'targetAttribute' => ['object_id', 'created_by']]
The created_by
attribute is generated with blameable behavior:
public function behaviors()
{
return [
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
];
}
The validating is done before the behavior input is stored in the model. (I know this, because if created_by
is required in the rules, the model will not save - validation error.)
Is there a good yii2-way to validate a behavior-generated attribute like this?
You can specify the events that the attributes will be created on by using the 'attributes' property of the behavior, so you can amend your model like this:
public function behaviors()
{
return [
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
'attributes' => [
ActiveRecord::EVENT_BEFORE_VALIDATE => ['updated_by', 'created_by']
]
],
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With