-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Closed
Description
Hi, I've just started reading a Yii2 guide about Model and get little confused about scenarios mentioned in Model::rules and Model::scenarios. I can't really understand why we need to scenarios in rules. From guide:
A)
function rules()
{
return [
// rule applied when corresponding field is "safe"
['username', 'string', 'length' => [4, 32]],
['first_name', 'string', 'max' => 128],
['password', 'required'],
// rule applied when scenario is "signup" no matter if field is "safe" or not
['hashcode', 'check', 'on' => 'signup'],
];
}
function scenarios()
{
return [
// on signup allow mass assignment of username
'signup' => ['username', 'password'],
'update' => ['username', 'first_name'],
];
}B)
"Sometimes, we want to mark an attribute as not safe for massive assignment (but we still want the attribute to be validated). We may do so by prefixing an exclamation character to the attribute name when declaring it in scenarios(). For example:
['username', 'password', '!secret']";Confusion: Isn't A) and B) the same?
I mean is A) and following code is equivalent?
function rules()
{
return [
// rule applied when corresponding field is "safe"
['username', 'string', 'length' => [4, 32]],
['first_name', 'string', 'max' => 128],
['password', 'required'],
// removed 'on'=>'signup'
['hashcode', 'check']
];
}
function scenarios()
{
return [
// on signup allow mass assignment of username,
// but also validate hashcode
'signup' => ['username', 'password', '!hashcode']";
'update' => ['username', 'first_name'],
];
}Thanks