Yii2:场景()模型方法 [英] Yii2: scenarios() model method

查看:28
本文介绍了Yii2:场景()模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个需要的功能:注册时设置密码和更改密码,如果用户忘记了密码.用户注册时,密码长度至少为4个字符;当更改通过时 - 至少 5 个字符.

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.

查看常见于注册和更改通行证.显然,还存在 2 个操作,其中使用了注册"或更改"两种情况.模型中的代码片段:

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'],
     ];
}

但我想通过scenarios()来实现.怎么做?我是 Yii 的初学者,所以不明白什么时候以及如何使用 scenarios().谢谢.

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.我需要将 scenarios() 用于具有 ONE 规则的 ONE 字段,但对这一规则使用 DIFFERENT 参数.如何在 Yii2 中定义场景? - 这不是我的情况.

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.

推荐答案

As 关于 scenarios() 的文档说:这个方法的默认实现将返回在 rules() 声明中找到的所有场景.所以通常你不需要覆盖这个方法,因为它会寻找 on 数组键来设置当前场景的活动属性并正确验证它们.

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.

所以在你的情况下 'on' =>对同一属性进行不同验证的某些场景"正是您所需要的.

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

这篇关于Yii2:场景()模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆