Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  181] [ 2]  / answers: 1 / hits: 24149  / 10 Years ago, fri, january 23, 2015, 12:00:00

I'm having a problem when submitting and validating a form by using a button outside the form, using Yii2.



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, how can I trigger directly the validation process before perform the submit manually? Maybe that will help me to control the submit process.


More From » php

 Answers
4

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.


[#68121] Tuesday, January 20, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;