Reset form without losing submitSucceeded - react-final-form

When using React Final Form, is there a way to reset the form without losing the submitSucceeded state. I want to display a success message on the form but I also want to clear it after a successful submit.

reset() clears all state. You could either:
a) Notice when submitSucceeded becomes true and save that state locally with setState(), or
b) Clear each field manually, with something like:
form.batch(() => {
form.change('firstField', '')
form.change('secondField', '')
form.change('thirdField', '')
// ...
})
Neither is incredibly elegant, but...

If you don't want to manually reset each field you can loop through all form posted values and reset each individually:
const submitForm = async (values, form) => {
// Do something on form submit here
// Reset form fields, note in a real world scenario
// this would be inside a success callback
Object.keys(values).forEach(key => {
form.change(key, undefined);
form.resetFieldState(key);
});
};

Related

How to change the sending message "Please wait..." of the form button after it is already loaded?

I'm calling a Mautic form using its token instead of a manual copy.
{form = 5}
When the form is submitted, the button text temporarily changes to "Please wait ...".
However, I need it to be a different text.
If I implement the form by manual copy, I could modify this message just by declaring this variable.
var MauticLang = {
'submittingMessage': "Another text"
}
I tried this in a script within the HTML where the form is, after and before it, also after the DOM is loaded, but there was no effect. I investigated the code on the page as much as I could, but to no avail. I have researched, but can't find a solution anywhere.
How to change the button sending message after the form is already loaded?
Modify submittingMessage value is the way to go.
MauticLang.submittingMessage = "Hold your horses...";
Or
MauticLang = {
'submittingMessage': "Hold your horses..."
}
In addition, to ensure that you are modifying it after Mautic is loaded, you can use setTimeOut with load event listener on window.
Something like 5 seconds, enough time to have the form not fully filled by the user.
So, the final solution could be:
window.addEventListener('load', function() {
setTimeout(function() {
MauticLang.submittingMessage = "Hold your horses..";
}, 5000);
});

best_in_place retains original values after update

I'm using best_in_place to do in-page editing of a table of data
in a ruby-on-rails app. The in-place editing works, but I have a
corner case that fails. A pair of items in the row (device_name,
generic_name) must be unique. If they are not unique, the server-side
code passes back a set of names with a changed generic_name to make
the pair unique. I use the following coffeescript to update the
display.
jQuery ->
$('.best_in_place[data-bip-object="full_dpoint"]').bind(
"ajax:success", (event, d) ->▫
return if ! d?
data = JSON.parse(d)
if ! data.dpoint?
return
else
item_to_edit = "#best_in_place_full_dpoint_" + data.dpoint.dpoint_id + "_generic_name"
$(item_to_edit).text(data.dpoint.generic_name)
)
This code works (IE it properly updates the page with the server-supplied
new generic name) , but if I then click back in the 'generic_name'
field, (to go into edit mode), the default edit text changes back
to what it was at the very beginning (page download time). I have
experimented with setting many different page elements to the new
generic name, including all of the following:
$(item_to_edit).attr('data-bip-original-content', data.dpoint.generic_name)
$(item_to_edit).attr('data-bip-value', data.dpoint.generic_name)
$(item_to_edit).attr('original-value', data.dpoint.generic_name)
$(item_to_edit).attr('bipValue', data.dpoint.generic_name)
$(item_to_edit).attr('bipvalue', data.dpoint.generic_name)
All to no avail. I have poked around in the dom trying to find where the original
value might be stored, but haven't found anything other than these.
Any ideas?
TIA.
Leonard
Try it
javascript:
$(document).ready(function () {
/* Activating Best In Place */
jQuery(".best_in_place").best_in_place();
var old_value;
$(document).on('change', '.not_abort', function (e) {
console.log(e.target.value);
old_value = e.target.value;
});
$(document).on('ajax:error', '.not_abort', function (e) {
console.log(e);
e.target.innerHTML = old_value;
$(e.target).data('bipOriginalContent', old_value);
});
})
view:
best_in_place #device_name, :email, class: 'not_abort'

What is the best way to disable elements in a form if it is signed?

I have a logic when users might be presented with a form values, but should be unable to change it if it is "signed". I am wondering what is the best way to do it from controller. Right now, all elements go through the loop and get "disabled" attribute if signature exist. I wonder if I can apply more elegant way on form creation.
This is what I have (and the "disabled" is not assigned to fieldsets this way):
EDIT 1 - added forms creation
$form = $sl->get('FormElementManager')->get($formName);
$hydrator = new DoctrineHydrator($objectManager);
$form->setHydrator($hydrator);
if($isSigned)
{
$formElements = $form->getIterator();
foreach($formElements as $element )
{
$element->setAttribute('disabled', 'disabled');
}
}

Rails 3, bootstrap modal multiple layers of remote calling

I've been racking my head against this for 2 days now. I'm massively frustrated, and I can't seem to find any information on this with searching.
The issue. I'm using a :remote => true link to load some html from a different controller.
$('.managed_locations').bind('ajax:complete', function(evt, xhr, status){
$('#locations_modal').modal('show')
$('#locations_modal').html(xhr.responseText);
});
So it gets the html, dumps it into the bootstrap modal and displays the modal. This is working fine.
But inside of the modal I ALSO have a form which also uses :remote => true. Now to make life harder, when a button is pressed I clone the form and display it. So the user could have many forms.
Now the issue. Whenever the form is submitted it just loads it like a normal page. It's as if the :remote => true is being ignored. But this only in the modal. If I just load the modal controller by itself it works just fine. I also had this developed before using another jquery lightbox where it was working fine. I'm just switching in bootstrap for consistency.
So my initial thoughts are that the jquery_ujs.js isn't finding the new forms. So I added some code to output the form elements.
$("#log_events").click(function () {
$(document).find(".new_stored_physical_location").each(function() {
console.log( $(this).data() );
console.log( $(this).data('events') );
});
return false;
});
Which outputs in the console:
Object { type="html", remote=true}
Object { ajax:complete=[1]}
So I see that the events are being set in jQuery. Each of these forms has :remote => true and has the ajax event for when the request is complete. But it's just not doing an ajax request when I hit submit.
Is there something I'm missing that is required to make sure an ajax request will happen from the form???? The data() looks fine, the data('events') look fine. But is there some other event/binding that I need to look at?
The html that is loaded in from the modal right now is loading a layout. But i've done it both with a layout, without a layout. It's driving me nuts. Thanks for the help guys.
Edit: Some extra weirdness. The modal also loads some additional remote links, all of which are working correctly. It's only the form links which don't seem to work.
I got a solution. The big issue was within jquery_ujs.js Especially this line:
$(document).delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
FYI, rails.formSubmitSelector = 'form'. So this code found all of the forms in the document, overwrote the submit with this function. But the issue was that once you loaded in some ajax, and that ajax contained a it wouldn't add this fancy event to it. You need to re-add it.
So this is what I did.
Inside of jquery_ujs there is a bunch of functions that are accessible outside of it using $.rails. So things like: $.rails.enableElement, $.rails.nonBlankInputs. And the code for the submit event was sitting around all willy nilly. It only executes once when the page is loaded. So I put that in a function addSubmitEvent():
// Add the form submit event
addSubmitEvent: function(element) {
//$(element) was before $(document) but I changed it
$(element).delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
var form = $(this),
remote = form.data('remote') !== undefined,
blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector),
nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
if (!rails.allowAction(form)) return rails.stopEverything(e);
// skip other logic when required values are missing or file upload is present
if (blankRequiredInputs && form.attr("novalidate") == undefined && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
return rails.stopEverything(e);
}
if (remote) {
if (nonBlankFileInputs) {
return rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
}
// If browser does not support submit bubbling, then this live-binding will be called before direct
// bindings. Therefore, we should directly call any direct bindings before remotely submitting form.
if (!$.support.submitBubbles && $().jquery < '1.7' && rails.callFormSubmitBindings(form, e) === false) return rails.stopEverything(e);
rails.handleRemote(form);
return false;
} else {
// slight timeout so that the submit button gets properly serialized
setTimeout(function(){ rails.disableFormElements(form); }, 13);
}
});
}
This is basically the exact same code. But now it's $(element) instead of $(document). This was changed because now I can sniff for when the modal has loaded in the html. Then I can call:
$.rails.addSubmitEvent('#my_modal');
I then had an issue of it adding the event too many times from when I opened/closed the modal multiple times. So I just put a simple true/false if around it to call it once only.

ASP.NET Remote Validation only on blur?

I'm using the remote validation in MVC 3, but it seems to fire any time that I type something, if it's the second time that field's been active. The problem is that I have an autocomplete box, so they might click on a result to populate the field, which MVC views as "leaving" it.
Even apart from the autcomplete thing, I don't want it to attempt to validate when they're halfway through writing. Is there a way that I can say "only run validation n milliseconds after they are finished typing" or "only run validation on blur?"
MVC 3 relies on the jQuery Validation plugin for client side validation. You need to configure the plugin to not validate on key up.
You can switch it globally off using
$.validator.setDefaults({
onkeyup: false
})
See http://docs.jquery.com/Plugins/Validation/Validator/setDefaults and the onkeyup option here http://docs.jquery.com/Plugins/Validation/validate.
For future reference, I found it's possible to do this in combination with the typeWatch plugin (http://archive.plugins.jquery.com/project/TypeWatch).
Basically what you want to do is (in my case for a slug):
/*Disable keyup validation on focus and restore it to onkeyup validation mode on blur*/
$("form input[data-val-remote-url]").on({
focus: function () {
$(this).closest('form').validate().settings.onkeyup = false;
},
blur: function () {
$(this).closest('form').validate().settings.onkeyup = $.validator.defaults.onkeyup;
}
});
$(function () {
/*Setup the typeWatch for the element/s that's using remote validation*/
$("#Slug").typeWatch({ wait: 300, callback: validateSlug, captureLength: 5 });
});
function validateSlug() {
/*Manually force revalidation of the element (forces the remote validation to happen) */
var slug = $("#Slug");
slug.closest('form').validate().element(slug);
}
If you're using the vanilla typeWatch plugin, you'll have to setup a typeWatch for every element because the typeWatch callback doesn't give you access to the current element via $(this), it only passes the value.
Alternatively you can modify the typeWatch plugin to pass in the element (timer.el) and then you can apply a delay to all.
For some reason (maybe because of conflicts with the unobtrusive plugin), hwiechers' answer didn't work for me. Instead, I had to get the validator of my form with .data('validator') (as mentioned in this answer) and set onkeyup to false on it.
var validator = $('#form').data('validator');
validator.settings.onkeyup = false;
We had the same problem of focusing out the autocomplete textbox "DealingWithContactName" when autocomplete suggestion list pops up. Here we select the dynamically generated autocomplete list item on which the user clicks and set focus on to it. After 50ms we take the focus out from the textbox. It solved our problem.
$('body').on('click', 'ul.ui-autocomplete li a', function () {
$('#DealingWithContactName').focus();
window.setInterval(function () {
$('#DealingWithContactName').blur();
}, 50);
});
I wanted local validation to remain during onkeyup so that the user had a tighter feedback loop. This should only affect the remote validation (that results from RemoteAttribute):
$("[data-val-remote]").keyup(function () {
// Avoid hitting server validation during onkeyup. Wait for onfocusout.
return false;
});

Resources