Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Model scene in Yii

Shulou Source: shulou.com Published: 2022-06-03 17:24:49 09月17日 Update

This article will explain in detail the example analysis of the model scene in Yii. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Preface

There is a concept of scenario in model field verification in Yii. Different verification rules can be set in different scenarios. The scene in Yii defaults to default. The simple implementation is as follows

Next, I will use the user table, and the fields in the table are user_name,password

The simple rules are as follows

Public function rules () {return ['user_name',' password'], 'required'], [[' user_name', 'password'],' string', 'max' = > 255],];}

One:

If we need to validate the user_name and password fields when we add them, we will only validate the user_name field when updating

At this point, we can override the yiibaseModel::scenarios () method in the model to customize the behavior.

Public function scenarios () {return ['create' = > [' user_name', 'password'], / / create means adding a scene' update' = > ['user_name'], / / update means updating a scene];}

According to the scene rules set above, we only need to set it to the specified scene when we add and update it.

/ / scene as an attribute to set $model = new User;$model- > scenario = 'create';// scene sets $model = new User ([' scenario' = > 'create']) by constructing an initialization configuration

According to the above, you can validate the specified fields in different scenarios.

Two:

We can use the on property in the rule rule to set different scenarios

Public function rules () {return ['id'],' integer'], [['user_name'],' required'], [['password'],' required', 'on' = >' create'] [['user_name',' password'], 'string',' max' = > 255],];}

According to the above, the password field is required in create scenarios.

Three:

Use yiibaseModel::validate () to validate the received data

$model = new User (); $model- > validate (['user_name'])

Use the validate method to verify user_name, and verify that true is returned, otherwise false is returned.

This is the end of the article on "sample analysis of model scenarios in Yii". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Scenarios validation fields models differences rules articles updates examples analysis as above properties methods more good practical two content preface data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information MariaDB Shulou Technology Docker OPPO Reno