5
votes

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
With 'can't be required' you mean those values cannot be accessed? Sure? Component::__get($name) looks for attributes in behaviours. I would expect that it should be accessible. Can you provide some code (esp. validation rules)? - robsch
With 'can't be required' i mean as a rule. If you require it in the rules, i wont save. So the validation is made before the behavior-input is added to the model. - Jørgen

1 Answers

5
votes

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']
            ]
        ],
    ];
}