PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 12, 2022

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

 March 12, 2022     rules, validation, yii, yii2     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing