I use ActiveForms often and find it handy as it includes client-side validation scripts yii.js and yii.activeForm.js. It normally takes care of model rules and basic validation on its own.
Until Yii 2.0.9:
We could use following script to prevent multiple form submission due to rapid button clicks:
$('form').submit(function(){
$(this).find('button[type!="button"],input[type="submit"]').attr("disabled",true);
setTimeout(function(){
$('form .has-error').each(function(index, element) {
$(this).parents("form:first").find(":submit").removeAttr("disabled");
});
},1000);
});
But,
Current Yii 2.0.10 release brought some changes and fails above script. Now, it will not submit the form if above code executes.
It has also been discussed earlier here and has been identified as bug.
Since, yii.js had two changes:
Bug #10358: Fixed race condition in yii.js AJAX prefilter (silverfire)
Enh #12580: Make yii.js comply with strict and non-strict javascript mode to allow concatenation with external code (mikehaertl)
and, yii.activeForm.js had four changes:
Bug #10681: Reverted fix of beforeValidate event calling in yii.activeForm.js (silverfire)
Enh #12376: Added parameter to yii.activeForm.js validate() method to be able to force validation (DrDeath72)
Enh #12499: When AJAX validation in enabled, yii.activeForm.js will run it forcefully on form submit to display all possible errors (silverfire)
Enh #12744: Added afterInit event to yii.activeForm.js (werew01f)
Can they be replaced with oder js files from v2.0.9?
Will replacing js files cause breakdown and unexpected behaviours?
Are there any better solution to prevent multiple submissions?
It looks like the issue had been taken care of, already.
Those who have installed fresh Yii 2.0.10 via composer will not have this issue; while, those who downloaded an archived file from 'Install from an Archive File' section may still have this issue since they might not have updated the archive files.
If you are facing this specific issue, then all you have to do is replace a specific file framework/assets/yii.activeForm.js from the github source.
In case of local copy, this file can be located at vendor\yiisoft\yii2\assets\yii.activeForm.js.
I suggest you to use uiBlocking to prevent multiple click or entries. Here is complte guide how to block ui while there is some task in progress.
http://malsup.com/jquery/block/
Works Like a Charm
I implemented and tested the following extension:
https://github.com/Faryshta/yii2-disable-submit-buttons
Composer Require
"faryshta/yii2-disable-submit-buttons": "*"
Register Asset Globaly
class AppAsset extends yii\web\AssetBundle
{
public $depends = [
'faryshta\\assets\\ActiveFormDisableSubmitButtonsAsset',
// other dependencies
];
}
Usage
$form = ActiveForm::begin([
'options' => ['class' => 'disable-submit-buttons'],
// other configurations
]);
// inputs
Html::submitButton('Submit', [
// optional, will show the value of `data-disabled-text` attribute
// while handling the validation and submit
'data' => ['disabled-text' => 'Please Wait']
])
$form->end();
Recently got some bug that my forms we not submiting, and button stayed disabled, so I changed it to this. Mostly posting it here for my future reference so I can find it out fast :D
<?php $this->registerJs("
$(function () {
$('body').on('submit', 'form', function() {
$(this).find('button[type!=\"button\"],input[type=\"submit\"]').attr('disabled',true);
setTimeout(function(){
$(this).find('.has-error').each(function(index, element) {
$(this).parents('form:first').find(':submit').removeAttr('disabled');
});
},1000);
});
});
", View::POS_END, 'prevent-double-form-submit'); ?>
Related
I'm a Back-end dev, and recently inherited a couple of legacy Apache Tapestry systems. My skills with Tapestry are null my knowledge on javascript medium.
I want to disable a submit button right before the submit is made to avoid multiple submits.
A very simple
$(document).ready(function () {
$("#form").submit(function () {
$("#submitbutton").attr("disabled", true);
return true;
});
});
approach wont do because the submit event is propagated before Tapestry does the client-side validation, so I could be disabling the button on a submint attempt that will fail validation.
On this question I learned that Tapestry also propagetes its own events, and if I could listen on tapestry:formprocesssubmit That would probably solve my problem.
I have my CreateContract.tml file with the form, fields and buttons that already work, I have my CreateContract.java file with
#Import(library = {
"context:js/jquery.mask.min.js",
"context:js/maintain-contracts.js",
"context:js/zone-overlay.js"},
stylesheet = "context:layout/zone-overlay.css")
And my maintain-contracts.js file with
$(document).ready(function () {
$("#form").on('tapestry:formprepareforsubmit', function () {
console.log("I want to arrive here!");
});
});
But it doesn't work.
On this mailing list thread I see people discussing very similar matters, but they go about listening on events on a different fashion, that I don't quite grasp.
Should I create the listener inside the initializer?
I'm reffering to the event as 'tapestry:formprepareforsubmit' instead of Tapestry.FORM_PREPARE_FOR_SUBMIT_EVENT because on both my maintain-contracts.js and my console the Tapestry variable is empty - why is that?
What about the .on versus .bind versus .observe trichotomy?
the first links's question was solved using ProptypeJS Class.create, but I think i dont have access to that.
I'm I going about that wrong?
Thank you, any help is appreciated.
Not an analysis of why your approach doesn't work, but a useful referral nonetheless:
Geoff Callender, creator of Tapestry JumpStart, has an excellent description of how duplicate form submissions can be avoided using a mixin.
See http://jumpstart.doublenegative.com.au/jumpstart/examples/javascript/creatingmixins1
After reading Tapestry's source code, i found out that the event is not called tapestry:formprepareforsubmit, but t5:form:prepare-for-submit, even though I found no documentation of that anywhere.
So
$(document).ready(function () {
$("#form").on('t5:form:prepare-for-submit', function () {
console.log("I want to arrive here!");
});
});
Works perfectly.
I'm working on a fairly simple form using crowd-html elements, which makes everything very simple. As part of our study, we want to see how workers interact with the form, so we have a bunch of basic JS logging. That is all prepared as a JSON and the idea is to log it using AWS API Gateway and AWS Lambda. The code all seems to work in unit tests, but not in the real form. I am trying to do this:
document.querySelector('crowd-form').onsubmit = function (e) {
if (!validateForm()) {
window.alert("Please check the form carefully, it isn't filled out completely!");
e.preventDefault();
} else {
let event_data = {
'specific_scroll_auditor': auditor_scrolled_pixels_specific.submit_callable(),
'specific_clicks_auditor': auditor_clicks_specific.submit_callable(),
'mouse_movements_total': auditor_mouse_movement_total.submit_callable(),
'on_focus_time': auditor_on_focus_time.submit_callable(),
'total_task_time': auditor_total_task_time.submit_callable(),
'focus_changes': auditor_focus_changes.submit_callable()
};
log_client_event('auditors', event_data);
post_event_log()
}
}
Note that the validation bit works, but the logging does not. I've tested post_event_log() on it's own, and that works just fine, so it seems like either 1) for some reason I never get to that else clause, or 2) the submission happens more quickly than I can call the logging functions. (but why, since the validation works?)
I also tried this, borrowed from the turkey code (https://github.com/CuriousG102/turkey) which was our inspiration.
$(window).ready(function () {
window.onbeforeunload = function () {
let event_data = {
'specific_scroll_auditor': auditor_scrolled_pixels_specific.submit_callable(),
'specific_clicks_auditor': auditor_clicks_specific.submit_callable(),
'mouse_movements_total': auditor_mouse_movement_total.submit_callable(),
'on_focus_time': auditor_on_focus_time.submit_callable(),
'total_task_time': auditor_total_task_time.submit_callable(),
'focus_changes': auditor_focus_changes.submit_callable()
};
log_client_event('auditors', event_data);
post_event_log()
}
});
That also doesn't work. I would prefer to do this in some simple way like what I have above, rather than completely rewrite the submit function, but maybe I have to?
your custom UI is placed inside a sandboxed iFrame by Ground Truth. It does that only for the real job, and not for previews (you're code might work while previewing the UI from AWS Console). The sandbox attribute on the iFrame goes like this
sandbox="allow-scripts allow-same-origin allow-forms"
Refer https://www.w3schools.com/tags/att_iframe_sandbox.asp for descriptions. Ajax calls are blocked regardless of the presence of allow-same-origin (not that you could change it in any way). See for a thorough explanation IFRAME sandbox attribute is blocking AJAX calls
This example might help.
It updates the onSubmit function to do some pre-submit validations.
https://github.com/aws-samples/amazon-sagemaker-ground-truth-task-uis/blob/master/images/keypoint-additional-answer-validation.liquid.html
Hope this helps. Let us know if not.
Thank you,
Amazon Mechanical Turk
I am doing CRUD for our website. Our implementation is to use submit but in some cases I need to pass data from JS file to my controller (BTW I am using Codeigniter) so I am now thinking if it is standard to use it at the same time. So far it works for me.
In my experience, pass it all through JS and basically do below. Note it's about as pseudo code as possible. You will need to make changes for it to even compile.
$("#submit").on('click', function(e) {
e.preventDefault();
if(normal_stuff()){
$(this).sumbit();
} else {
fancy_stuff();
}
});
I made myself a custom validator, that works exactly as I want with AngularJS 1.2 but now I would like to upgrade to the latest and almost stable version of 1.3 but after debugging for some time I found that it doesn't work as expected because I use both $timeout with inside a ctrl.$setValidity. My original and working code (of course it's just a subset of the actual code) is the following:
var validator = function(value) {
// invalidate field before doing any validation,
// so that it's invalid before typing timeout has time to finish and execute
ctrl.$setValidity('validation', false);
$timeout.cancel(timer);
timer = $timeout(function() {
var isValid = validate(value);
ctrl.$setValidity('validation', isValid);
}, 1500);
return value;
}; // end of validator()
// attach the Validator object to the element
ctrl.$parsers.unshift(validator);
ctrl.$formatters.unshift(validator);
I manually change the $setValidity to false because I want to make sure that the user will not post the form before the field is actually finished validated. The timeout is there only so that it gives the user a smoother experience by displaying the error (if there is) only after he finished typing (or at least stop typing after 1.5sec). After that timeout of 1.5sec is finished, the validate(value) kicks in and should update the $setValidity to true or false... This is working perfectly fine in AngularJS 1.2 but not at all in 1.3. Even if I manually set the $setValidity to true by myself it doesn't work and actually stays to a false state, but if I remove the $timeout wrapper, then it's working fine.... but I really need and want my timeout to work! For a reference point of view, my custom validator is available freely to anyone at this Github link
Any help is greatly appreciated.
EDIT
After having help from #SKYWALKR (thanks for starting help), I further went to debug my problem and it is actually much more than what I described at first. My problem seems in fact related to a bunch of things all together, ng-model binding inside ng-repeat that execute a custom validator which has problem only if I enable the $timeout... now with all that together, the binding does not function correctly, wow took me a while to build a proper testing case for this. So here is the sample of my problem: plunker
When you run the sample at first, you will see that none of the Output A:{{binding}} is working (it's suppose to display whatever you type just below it) that it does not work, but then if you comment out the var timer and $timeout (comment out line 39, 42 and 44) and then run it again, now it works...so why? what's broken?
Your correct, 1.3 is not a stable release as of yet. Your directive works fine using 1.3.0-rc.0...see plunkr below.
http://embed.plnkr.co/GSU2Ldn0D2YM0aD9PQla/preview
I have a complex form requiring me to switch specific validators on or off depending on selections made by the user.
ValidatorEnable seems to do the job, but it seems that when I call this method it actually fires the validation process as well, without the user actually hitting the submit button.
Is that how it works?
I eventually found the best way to do this was to use the following code:
var validatorObject = document.getElementById('<%=ValidHasShippingLocationZip.ClientID%>');
validatorObject.enabled = false;
validatorObject.isvalid = true;
ValidatorUpdateDisplay(validatorObject);
I wrote some code seems can meet your requests.
Iterate validators and enable these you needs.
ValidatorEnable(validatorObj, true);
then clear the screen,erase the error info.
The full code snippet can be found here http://codelife.cybtamin.com/enable-and-disable-asp-net-validator-by-javascript/