Saturday, March 12, 2022

[FIXED] YII validation rules required - how required rule works

Issue

I am starting with Yii and I dont understand when or how required rule in model rules works.

I have an article table with cols title, slug, body, created_at.

The slug and created_at cols are generated in php, so they are not required and are not the part of the create form. If I leave created_at in the required rule it throws an error cause value is missing. But if I leave slug in required rule it does not throw an error and it works. But there is no value for slug cause it is generated later in Php.

So the question is if required rule is validated on POST data or when it is inserted to DB or ...? Here is the model code with rules and behaviors:

public function rules()
{
    return [
        //[['title', 'created_at', 'body'], 'required'],  // THIS THROWS AN ERROR cause created_at is not in POST
        [['title', 'slug', 'body'], 'required'],  // THIS SHOULD THROW AN ERROR cause slug is not in POST but it works. Why?
        [['body'], 'string'],
        [['created_at', 'updated_at', 'created_by'], 'integer'],
        [['title', 'slug'], 'string', 'max' => 100],
        [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['created_by' => 'id']],
    ];
}

public function behaviors()
{
    return [
        TimestampBehavior::class,
        [
            'class' => BlameableBehavior::class,
            'updatedByAttribute' => FALSE,
        ],
        [
            'class' => SluggableBehavior::class,
            'attribute' => 'title',
        ]
    ];
}

Solution

SluggableBehavior and TimestampBehavior are using different events:

  1. SluggableBehavior is using ActiveRecord::EVENT_BEFORE_VALIDATE so slug is generated before validation, thus required rule does not complain about missing slug since it is no longer empty.
  2. TimestampBehavior is using ActiveRecord::EVENT_BEFORE_INSERT and ActiveRecord::EVENT_BEFORE_UPDATE events which are executed after validation, so at the moment of validation fields with dates are empty.


Answered By - rob006

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.