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'] ]; }
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 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 entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
yii2 implements paging and paging functions with search
How to implement the Yii framework output execution on the page sql statement and debugging
The above is the detailed content of Simple use of scenes in Yii2. For more information, please follow other related articles on the PHP Chinese website!