phpyii2yii2-validation

Yii2, why a model validation fails due to a missing mandatory attribute when that attribute is assigned by a Behavior?


I have a Model with a
[['creation_time'], 'integer'] attribute which have a

[
    'class' => TimestampBehavior::className(),
    'createdAtAttribute' => 'creation_time'
]

behavior assigned.
If I mark this attribute as required it'll fail the model validation as if it's missing.
Why?
How can I mark it as required?


Solution

  • The problem is in order in which the actions are performed.

    The creation_time attribute is set by yii\behaviors\TimestampBehavior during the BaseActiveRecord::EVENT_BEFORE_INSERT. This event is invoked by beforeSave() callback.

    If you take a look at souce code of insert() method in ActiveRecord you can see the order of actions is:

    1. Validate
    2. Call beforeSave
    3. Do the insert
    4. Call afterSave

    So your model is first validated and then the creation_time is set. That's why validation of this attribute is failing.

    If your creation_time is only set by TimestampBehavior then there is no need to validate it. If you want to allow editation of this attribute, then you can use scenarios to validate it only during editing.