Briefly introduce the usage scenarios of Yii2

怪我咯
Release: 2023-03-10 14:46:02
Original
1387 people have browsed it

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. .

This article mainly introduces the relevant content about the use of Yii2 in simple scenarios. It is shared for everyone’s reference and learning. Let’s take a look at the detailed introduction:

Go directly Code (main part):

Model layer:

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

Controller:

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

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的都不会验证
 ];
}
Copy after login

The result is: the username is not verified, the password is 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 exist in the scenarios() method, otherwise an error will occur!

The above is the detailed content of Briefly introduce the usage scenarios of Yii2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template