问题
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?
回答1:
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 controller 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']
]
],
];
}
来源:https://stackoverflow.com/questions/29282401/validation-rules-on-behavior-created-attributes