ActiveForm,字段的自定义 ID 破坏了验证

ActiveForm, custom id for field broke validation

我是 Yii2 的新手,遇到了下一个不愉快的问题。

我在同一个页面创建了两个表单,如

<?php $form = ActiveForm::begin([
        // make sure you set the id of the form
        'id' => 'create',
        'action' => $action,
        'options' => ['enctype' => 'multipart/form-data']
    ]); ?>

    <?php $form = ActiveForm::begin([
        // make sure you set the id of the form
        'id' => 'update',
        'action' => $action,
        'options' => ['enctype' => 'multipart/form-data']
    ]); ?>

我对两个表单字段使用相同的模型,例如

<?=  $form->field($action_model, 'action_name',[
                'addon' => ['prepend' => ['content'=>$action_model->getAttributeLabel('action_mobile')]]
            ])->widget(Typeahead::classname(), [
                'options' => ['placeholder' => $action_model->getAttributeLabel('action_placeholder')],
                    'pluginOptions' => ['highlight'=>true],
                    'dataset' => [
                        [
                        'local' =>  Json::encode( $totalLookUp['action_lookUp'] ),
                        'limit' => 10
                        ]
                    ]
                ])->label(false);
            ?>

这就是问题所在。在那种情况下,我有两个具有相同字段范围、相同名称和相同 ID 的表单。肯定对 W3C 无效。另一个问题是,尽管客户端预先提交了两种形式的 javascript 验证,但效果很好。 typeahed 小部件仅适用于第一组字段,因为它由 id 绑定。

如果我尝试通过

等小部件选项指定它来覆盖元素 ID
<?=  $form->field($action_model, 'action_name',[
                'addon' => ['prepend' => ['content'=>$action_model->getAttributeLabel('action_mobile')]]
            ])->widget(Typeahead::classname(), [
                'options' => ['id'=> $form_id.'_action_name',
'placeholder' => $action_model->getAttributeLabel('action_placeholder')],
                    'pluginOptions' => ['highlight'=>true],
                    'dataset' => [
                        [
                        'local' =>  Json::encode( $totalLookUp['action_lookUp'] ),
                        'limit' => 10
                        ]
                    ]
                ])->label(false);
            ?>

typeahead 工作完美,但在那种情况下验证失败,我的意思是它停止工作。

所以问题是,如何调整验证脚本并使用唯一的表单 ID。

来自docs

If you set a custom id for the input element, you may need to adjust the $selectors accordingly.

针对您的情况:

$form->field($action_model, 'action_name', [
    'selectors' => ['input' => '#'.$form_id.'_action_name'],
    'addon' => ...