简体   繁体   English

Yii2:使用表单外部的按钮提交并验证表单

[英]Yii2: Submit and validate a form by using a button outside the form

I'm having a problem when submitting and validating a form by using a button outside the form, using Yii2. 使用Yii2在表单外部使用按钮提交和验证表单时遇到问题。

This is my case: 这是我的情况:

I have a form ( myForm ) and a submit button ( myButton ) inside of that form. 我在该表单内部有一个表单( myForm )和一个提交按钮( myButton )。 When I click the myButton the validation is performed and if validation fails, then the submit is not performed. 当我单击myButton时,将执行验证,如果验证失败,则将不执行提交。 This is expected, of course, and it works. 当然,这是可以预期的,并且可行。

However, What I really want is to submit myForm by clicking on myButton which is outside the form element. 但是,我真正想要的是通过单击位于表单元素外部的myButton提交myForm To acomplish this I simply call jQuery('myForm').submit(), and the submit works. 为此,我只需调用jQuery('myForm')。submit(),然后提交工作即可。

The problem I face with this last scenario, is that the validation fails but the form is yet submitted, which is not expected. 我在最后一种情况下面临的问题是,验证失败,但是表单尚未提交,这是不期望的。

How can I submit a form with a button outside the form, and make the validation work too? 如何提交带有表单外部按钮的表单,并使验证也起作用?

This is my view: 这是我的看法:

<?php

    $form = ActiveForm::begin([
            'validateOnSubmit' => true,
            'type' => ActiveForm::TYPE_VERTICAL,
            'options' => ['class' => 'main-task-form']
        ]);

    echo Form::widget([
            'model' => $modelData,
            'form' => $form,
            'columns' => 2,
            'attributes' => [
                'closeDate' => [
                        'type'=> 'widget',
                        'widgetClass'=> DatePicker::className(),
                        'options'=>[
                            'type' => DatePicker::TYPE_COMPONENT_APPEND,
                            'pluginOptions' => [
                                'autoclose' => true,
                                'language' => 'es',
                                'format' => 'dd-mm-yyyy',
                                'todayBtn' => 'linked',
                            ],
                        ],
                    ],
                'descriptionClose' => [
                    'type'=>'textarea', 
                    'options' => [
                        'rows' => 3,
                    ],
                ],
            ],
        ]);
?>



<?php ActiveForm::end() ?>
<!-- Form Ends Here -->


<!-- Submit Button Outside Form -->
<?= Html::button('Completar Tarea', ['class' => 'btn btn-primary btn-task-form']) ?>

And this is the Javascript code to tell the button outside the form, to trigger the submit: 这是Javascript代码,用于告知表单外部的按钮,以触发提交:

function assignCompleteButtonToTaskForm ()
{

    var completeButton = jQuery ('button.btn-task-form')[0];
    var mainTaskForm = jQuery ('form.main-task-form')[0];

    completeButton.onclick = function (e) {
        mainTaskForm.submit ();
    }
}

Any idea about this? 有什么想法吗?

Also, how can I trigger directly the validation process before perform the submit manually? 另外,如何在手动执行提交之前直接触发验证过程? Maybe that will help me to control the submit process. 也许这将有助于我控制提交过程。

You can also manually trigger the validation of the form in Yii way, with following javascript code 您还可以使用以下javascript代码以Yii方式手动触发表单的验证

$('#form-id').yiiActiveForm('submitForm');

This will validate the form and returns true if there are no validation errors otherwise false . 这将验证表单,如果没有验证错误,则返回true ,否则返回false

So you can combine this and form submit calls to achieve desired behaviour. 因此,您可以将其与表单提交调用结合起来以实现所需的行为。

Also, sometimes its good idea to dive into the code and see how things are working internally, you can see how yii is handling most of its active form stuff in frontend in yii.activeForm.js , Im sure you won't regret it. 另外,有时候深入研究代码并查看内部工作情况是一个好主意,您可以在yii.activeForm.js的前端中看到yii如何处理其大多数活动表单内容,我确定您不会后悔。

Well you can just do it by using jQuery. 好吧,您只需使用jQuery即可。

jQuery(document).ready(function($){
   // Set Button ID or class replacing # to .  
    $("#you_button_id").on('click', function(event){
         // When you click on this button don't do any thing.
         event.preventDefault();
         // Set form ID and submit that form
         $("#your_form_id").submit();
    });
})

try if it works. 尝试是否可行。

I happen to have the same situation in my code and I use a combination of both other answers: 我的代码中碰巧遇到相同的情况,我同时使用了其他两个答案:

$(document).ready(function() {
   var $form = $('#form_id");
   $form.on('submit', function(e) {
      return $form.yiiActiveForm('submitForm');
   }); 

   $('#submit_button_id").on('click', function() { 
      $form.submit();
   });
});

The reason you have to call submitForm yourself (if you want to validate once more before submit) is because the default Yii2 implementation binds the call of this function to submit inputs within the form. 您必须自己调用submitForm的原因(如果要在提交之前再次验证)是因为默认的Yii2实现将此函数的调用绑定为在表单内提交输入。 This means it won't be called for an external trigger. 这意味着不会为外部触发器调用它。

I found a solution to my problem, combining some of your previous answers. 通过结合您以前的一些答案,我找到了解决问题的方法。 Now I'm able to trigger form validation and request a confirmation correctly as expected initially. 现在,我能够触发表单验证并正确地按照最初的期望请求确认。 See the final code . 请参阅最终代码 Thanks for the help. 谢谢您的帮助。

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

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