Hi there. I’m having a problem and I came here for your humble help. This is my case:
I have a form (myForm) and a submit button (myButton) inside of that form. When I click the myButton the validation is performed and if validation fails, then the submit is not performed. 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. To acomplish this I simply call jQuery(‘myForm’).submit(), and the submit works.
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:
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, can I trigger directly the validation process before perform the submit manually? Maybe that will help me to control the submit process.