如何在yii2中应用更新规则

时间:2018-04-01 03:50:22

标签: yii yii2 updates rules

我是yii2的新手,我并不完全知道如何将相同的插入规则应用到更新中。这是我的插入规则,我希望所有规则也对更新产生影响。

    public $tag;
    public function rules()
{
    return [
        [['user_id', 'name', 'address', 'state'], 'required'],
        [['user_id'], 'integer'],
        [['tag'], 'safe'],
        [['name'], 'string', 'max' => 30],
        [['address'], 'string', 'max' => 250],
        [['state'], 'string', 'max' => 255],
    ];
}

添加' on' => '更新'不会影响我的代码。对不起我的英语不好。感谢。

2 个答案:

答案 0 :(得分:1)

默认规则适用于创建和更新,如果您希望更新和创建之间有不同的行为,则只需创建新规则。

要应用规则,只需要$model->validate()检查规则,请参阅yii2文档示例

$model->load(\Yii::$app->request->post());

if ($model->validate()) {
    // all inputs are valid
} else {
    // validation failed: $errors is an array containing error messages
    $errors = $model->errors;
}

答案 1 :(得分:1)

您可以将验证规则添加到yii模型中,如此

public function rules(){
        return [
        [['boolean_var'],'boolean'],
            [[ 'range_in_string'],'required'],
            [['default_value'],'default','value'=>'DEFAULT VALUE'],
            [['integer_var'],'integer'],
            [['double_var'],'double'],
            [['number_min'],'number','min'=>10],
            [['number_max'],'number','max'=>100],
            [['number_min_max'],'number','min'=>10,'max'=>100],
            [['file_image'],'image'],
            [['file_var'],'file','types'=>['gif','jpg']],
            [['date_var'],'date', 'format'=>'d-m-yy'],

            [['min_string'],'string','min'=>10],
            [['max_string'],'string','max'=>10],
            [['min_max_string'],'string','min'=>5,'max'=>10],
            ['min_max_string2', 'string', 'length' => [4, 10]],

            ['email_var','email'],
            ['url_var','url'],

            [['unique_var'],'unique'],

            [['filter_trim'],'filter','filter'=>'trim'],
            [['filter_trim'],'filter','filter'=>'strtolower'],
            ['filter_custom_function', 'filter', 'filter' => function ($value) {
            // your concept
            if($value=='')
            return '';
            return 'Value Changed';}],

            ['range_in_min_max', 'in','range'=>range(5,20)],

            ['range_in','in','range'=>['en','fr','zn'],'strict'=>false], //strict false
            ['range_in_string','in','range'=>['EN','FR','ZN'],'strict'=>true],

            ['custom_validation','custom_function_validation'],

            [['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],     
            [['password','date_var'],'safe'],
        ];
}

如果您只需要在更新但不创建时触发,则可以添加这样的场景

public function rules()
{
    return [
        // username, email and password are all required in "update" scenario
        [['username', 'email', 'password'], 'required', 'on' => 'update'],

        // username and password are required in "login" scenario
        [['username', 'password'], 'required', 'on' => 'login'],
    ];
}

并在调用validate之前的操作中添加方案

//场景设置为属性

$model = new User;
$model->scenario = 'update';