································场景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



木木先生
26 声望4 粉丝

下一篇 »
php设计模式