-1

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?

1 Answers1

2

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.

Michal Hynčica
  • 2,925
  • 1
  • 4
  • 17