Yii2: scenarios() model method

半城伤御伤魂 提交于 2019-12-10 20:15:32

问题


There are 2 needed functions: set password when registering and change password, if user forgot it. When user signs up, password length must be at least 4 chars; when changes pass - at least 5 chars.

View is common for registration and changing pass. Obviously, also 2 actions exist, in which either scenario 'signup', either 'change' used. Code snippet in model:

public function rules() {
     return [
       ['password', 'string', 'min' => 4, 'on' => 'signup'],
       ['password', 'string', 'min' => 5, 'on' => 'change'],
     ];
}

But I want to do do it via scenarios(). How to do it? I'm a beginner in Yii, so did not understand, when and how to use scenarios(). Thanks.

UPD. I need to use scenarios() for ONE field with ONE rule, but DIFFERENT arguments to this one rule. how to define a scenario in Yii2? - it is NOT my case.


回答1:


As documentation about scenarios() says: The default implementation of this method will return all scenarios found in the rules() declaration. So generally you do not need to override this method, because it will look for on array keys to set active attributes for current scenario an validate them properly.

So in your case 'on' => 'some scenario' for different validations of the same attribute is exactly what you need.



来源:https://stackoverflow.com/questions/31252747/yii2-scenarios-model-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!