Home  >  Article  >  Backend Development  >  A brief introduction to scenarios in Yii2

A brief introduction to scenarios in Yii2

*文
*文Original
2018-01-03 13:38:49912browse

This article mainly introduces to you the relevant information about the use of simple scenarios in Yii2. The introduction in the article is very detailed and has a certain reference and learning value for everyone. Friends who need it can follow the editor to learn together. I hope to be helpful.

Directly upload the code (main part):

Model layer:

public function rules()
{
 return [
  [['name', 'account', 'pwd'], 'string', 'max' => 11],
  ['account','required','message'=>'用户名不能为空'],
  ['pwd','required','message'=>'密码不能为空','on'=>'update']
 ];
}

Controller:

$model = new User();
if(isset($_POST['User'])){
 $model -> attributes = Yii::$app->request->post('User');
 $model -> save();
}

No scene is called in the controller at this time. The result is: username verification, password not verification

If you add a sentence$model->scenario='update';to the controller, the result is: user The name and password have been verified

If you add a few lines of code to the model at this time:

public function scenarios()
{
 return [
  'update'=>['pwd'],//在该场景下的属性进行验证,其他场景和没有on的都不会验证
 ];
}

The result is: the user name has not been verified, and the password has not been verified. Verified

Also note that if you override the scenarios() method in the model and call the scene in the controller, the scene name called must be in the scenarios() method Yes, otherwise an error occurs!

Related recommendations:

Detailed explanation of the use of scenarios in Yii2

Detailed explanation of how the Yii framework implements logging to custom files

Detailed explanation of the use of Yii2 form widgets

The above is the detailed content of A brief introduction to scenarios in Yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn