Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation rules on behavior-created attributes

Tags:

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']]

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?

like image 563
Jørgen Avatar asked Mar 26 '15 15:03

Jørgen


1 Answers

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']
            ]
        ],
    ];
}
like image 93
Joe Miller Avatar answered Oct 11 '22 13:10

Joe Miller