行为创建属性的验证规则 [英] Validation rules on behavior-created attributes
问题描述
我有一个模型,其中包含两个必须唯一的值.Yii2 对此有一个验证规则:
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']]
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',
],
];
}
在将行为输入存储在模型中之前完成验证.(我知道这一点,因为如果规则中需要 created_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.)
是否有一种好的 yii2 方法来验证这样的行为生成的属性?
Is there a good yii2-way to validate a behavior-generated attribute like this?
推荐答案
您可以使用行为的 'attributes' 属性指定将在其上创建属性的事件,因此您可以像这样修改您的模型:
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']
]
],
];
}
这篇关于行为创建属性的验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!