乐趣区

yii场景使用

································场景 1································ 控制器:
$model->scenario=’update’;// 指定场景
$model -> save();

模型中:
public function rules() {
return [
[‘name’,’required’,’message’=>’ 用户名不能为空 ’],
[‘age’,’required’,’message’=>’ 年龄不能为空 ’,’on’=>’create’],
[‘pwd’,’required’,’message’=>’ 密码不能为空 ’,’on’=>’update’]
];
}

结果:
验证 name 和 pwd

································场景 2································ 控制器:
$model->scenario=’update’;
$model -> save();

模型中:
public function rules(){
return [
[‘name’,’required’,’message’=>’ 用户名不能为空 ’],
[‘age’,’required’,’message’=>’ 年龄不能为空 ’,’on’=>’create’],
[‘pwd’,’required’,’message’=>’ 密码不能为空 ’,’on’=>’update’],
[‘level’,’required’,’message’=>’ 等级不能为空 ’,’on’=>’update’],
];
}
public function scenarios(){
return [
‘update’=>[‘pwd’],
]
}

结果:
验证 pwd

································场景 3································ 控制器:
$model -> save();

模型中:
public function rules(){
return [
[‘name’,’required’,’message’=>’ 用户名不能为空 ’],
[‘age’,’required’,’message’=>’ 年龄不能为空 ’,’on’=>’create’],
];
}

public function scenarios(){
return [
‘update’=>[‘pwd’],
];
}

结果:
报错,缺少场景

································场景 4································ 控制器:
$model -> save();

模型中:
public function rules(){
return [
[‘name’,’required’,’message’=>’ 用户名不能为空 ’],
[‘level’,’required’,’message’=>’ 等级不能为空 ’],
[‘age’,’required’,’message’=>’ 年龄不能为空 ’,’on’=>’create’],
];
}
public function scenarios(){
return [
‘update’=>[‘pwd’],
‘default’=>[‘name’]
];
}

结果:
验证 name

································场景 5································ 控制器:
$model -> save();

模型中:
public function rules(){
return [
[‘name’,’required’,’message’=>’ 用户名不能为空 ’],
[‘age’,’required’,’message’=>’ 年龄不能为空 ’,’on’=>’create’],
];
}

结果:
验证 name

退出移动版