简体   繁体   English

以Yii2格式更改方案

[英]Change scenario in form Yii2

I want to change scenario in view page by jQuery. 我想通过jQuery更改视图页面中的方案。 There is a checkbox in my form, I want inputbox be required in checked checkbox. 我的表单中有一个复选框,我希望选中的复选框中需要输入框。

my rule: 我的规则:

public function rules() {
        return [
               .
               .
               .
               ['pass' , 'required', 'on'=> 'checked']
        ]
}

my view page: 我的查看页面:

<?=$form->field($model, 'check')->checkbox()?>
<?=$form->field($model, 'Pass')->textInput(['maxlength' => 20])?>

Try to set up your rule like this: 尝试像这样设置您的规则:

public function rules() {
    $checkBoxID = Html::getInputId($this, 'check');

    return [
        /* other rules */
        ['pass' , 'required', 
            'when' => function($model) {
                return $model->check;
            },
            'whenClient'=> "function(attribute, value){
                return $('#{$checkBoxID}').prop('checked');
            }",
            'on' => 'checked'
        ],
    ];
}

Read about conditional validation and whenClient validator property . 阅读有关条件验证whenClient validateator属性的信息 Also consider naming you scenario more informative, eg by its purpose, like 'on' => 'sign-up' , or 'on' => 'login' . 还可以考虑给您的场景命名更多信息,例如,按其目的命名,例如'on' => 'sign-up''on' => 'login' Scenario is useful when you need certain rules to apply in particular cases, but you need to specify this scenario explicitly. 当您需要在某些情况下应用某些规则但需要显式指定此方案时,方案非常有用。 Either when you instantiate a model 实例化模型时

$model = new MyModel();
$model->scenario = 'sign-up';

and passing it into a view, or before doing any validation after $model->load($data) 并将其传递到视图中,或者在$model->load($data)之后进行任何验证之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM