I'm trying to run some js code before a AEM CQ Dialog submit event. I achieved it handling next event:
$(document).on("click", ".cq-dialog-submit", function (e) {
e.stopPropagation();
e.preventDefault();
//More code
$(this).closest("form.foundation-form").submit();
});
This works, but is skipping the AEM form validation and lets required fields to go empty.
Any idea to add an action just after the fields are valid, but to control when the submit must go?
Thanks!
You can try to use pre submit hook
$(window).adaptTo("foundation-registry").register("foundation.form.submit", {
selector: "*",
handler: function () {
// custom code
}
});
It will be executed before every TouchUI Dialog submit and after all validations
Related
I'm having trouble testing a form submit event using React, TestUtils and Jest.
I have a component that renders a <form> DOM element; the same component also has a method that handles the onSubmit event and logs a statement. My goal is to mock the onSubmit handler and assert that it is called.
form-component.cjsx
module.exports = React.createClass
# Handle form submissions
handleSubmit: (e) ->
console.log 'Make async call'
# Render a form
render: ->
<form onSubmit={#handleSubmit}>
<input type="submit" />
</form>
__tests__/test-form-component.coffee
jest
.dontMock '../form-component'
React = require 'react/addons'
TestUtils = React.addons.TestUtils
FormComponent = require '../form-component'
describe 'FormComponent', ->
it 'creates a log statement upon form submission', ->
# Render a FormComponent into the dom
formInstance = TestUtils.renderIntoDocument(<FormComponent />)
# Mock the `handleSubmit` method
formInstance.handleSubmit = jest.genMockFunction()
# Simulate a `submit` event on the form
TestUtils.Simulate.submit(formInstance)
# TestUtils.Simulate.submit(formInstance.getDOMNode()) ???
# I would have expected the mocked function to have been called
# What gives?!
expect(formInstance.handleSubmit).toBeCalled()
Related Questions:
Test a React Component function with Jest
Test a form with Jest and React JS TestUtils
What seems to be your issue exactly?
React.addons.TestUtils.Simulate.submit() works for me.
If it can help, I was in similar situation and I testing the submit handler this way (using sinon.js, mocha and chai):
var renderDocumentJQuery = $(renderDocument.getDOMNode())
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
renderDocumentJQuery.find('input#person_email').val('test#email.com');
React.addons.TestUtils.Simulate.submit(renderDocumentJQuery.find('form')[0]);
var requestFired = requests[0];
this.xhr.restore();
it('should fire an AJAX with the right params', function(){
assert.equal(requestFired.requestBody,'campaign_id=123&owner_id=456&person%5Bemail%5D=test%40email.com')
});
it('should fire an AJAX with a POST method', function(){
assert.equal(requestFired.method,'POST')
});
it('should fire an AJAX with the correct url', function(){
assert.equal(requestFired.url,'url-for-testing')
});
There's an issue with the way React calls event handlers that causes the original handler function to continue to be called even if you attempt to mock it first.
This can apparently be avoided by switching to the ES6 class syntax to create component classes, but another simple workaround is to have the event handler just call a second function and mock that. For example:
onSubmit: function() {
this.handleSubmit(); // extra fn needed for Jest
},
handleSubmit: function(){
this.setState({
submitted: true
});
}
You would set the form's onSubmit={this.onSubmit} and mock handleSubmit instead of onSubmit. Since this introduces a seemingly unnecessary extra function, if you decide to do this it's probably worth adding a comment to anticipate later attempts to "fix it" which would break the test.
I'm trying to call a function after any form with the class shown below is submitted. However, this doesn't seem to be working for me (the form submits, but the submit button remains active and the loading image is not shown).
$(document).ready(function() {
$('.uniForm').submit(function() {
$('#loadingImage').show();
$(':submit',this).attr('disabled','disabled');
return true;
});
});
Here's some HTML:
<form class="uniForm" id="formABC">
//...form.... here
</form>
<img src="loadimage.gif" style="display: none;" id="loadingImage">
does anyone see anything inherently wrong with this that would be preventing things from working correctly?
I have a feeling it's just not being called correctly. Can I call it myself via some HTML like this?
<button type="button" class="primaryAction" alt="Submit Form" onclick="$('#formABC').submit();">Submit Form</button>
Following your comment, it seems the binding of the handler function to the submit event might be taking place before the form element has been loaded into the DOM.
Ideally, you should bind event handlers only after the DOM has finished loading.
For example:
$(document).ready(function() {
$('.uniForm').submit(function() {
...
});
});
Put an id on the submit input/button and try this:
$('#mySubmitButton').click(function(e) {
e.preventDefault();
e.stopPropagation();
$(this).attr('disabled','disabled');
$('#loadingImage').show(function() {
$(this.form).submit();
});
});
There is a jQuery plugin named jQuery Form Plugin which helps to submit your form from ajax without refresh and then you can do the rest of actions on its success (which occurs exactly after successful form submission):
jQuery(document).ready(function () {
jQuery('#my_submit_button').click(function (e) {
jQuery(this.form).ajaxSubmit({
target: false,
success: function ()
{
your_other_stuff();
},
});
});
});
function your_other_stuff(){
// rest of things
}
Try something else:
$('.uniForm input[type=submit]').click(function(){
$('.uniForm').submit();
//doStuffafterSubmit
});
Presently, a messagebox appears with the failing class name:
Is it possible to override the default behavior in Alfresco? Could we use forms service to present a different message ?
Additional to zladuric answer,
you can use failureCallback method to show message what you want.
But it is difficult to search failureCallback method of workflow forms for a new one because workflow forms such as "Start Workflow", "Task Edit", "Task Detail" are used form engine.
For example, in "Start Workflow" form, you can add our own successCallBack and failureCallBack by writing onBeforeFormRuntimeInit event handler in start-workflow.js like this.
onBeforeFormRuntimeInit: function StartWorkflow_onBeforeFormRuntimeInit(layer, args)
{
var startWorkflowForm = Dom.get(this.generateId + "-form");
Event.addListener(startWorkflowForm, "submit", this._submitInvoked, this);
args[1].runtime.setAJAXSubmit(true,
{
successCallback:
{
fn: this.onFormSubmitSuccess,
scope: this
},
failureCallback:
{
fn: this.onFormSubmitFailure,
scope: this
}
});
}
onFormSubmitSuccess: function StartWorkflow_onFormSubmitSuccess(response)
{
this.navigateForward(true);
// Show your success message or do something.
}
onFormSubmitFailure: function StartWorkflow_onFormSubmitFailure(response)
{
var msgTitle = this.msg(this.options.failureMessageKey);
var msgBody = this.msg(this.options.failureMessageKey);
// example of showing processing response message
// you can write your own logic
if (response.json && response.json.message)
{
if(response.json.message.indexOf("ConcurrencyFailureException") != -1)
{
msgTitle = this.msg("message.concurrencyFailure");
msgBody = this.msg("message.startedAgain");
}
else
msgBody = response.json.message;
}
Alfresco.util.PopupManager.displayPrompt(
{
title: msgTitle,
text: msgBody
});
}
Since Alfresco.component.StartWorkflow(in start-workflow.js) extends Alfresco.component.ShareFormManager(in alfresco.js). You can override onBeforeFormRuntimeInit event in start-workflow.js. I hope this your help you.
I'm not looking at the code right now, but this looks like a regular YUI dialog. So it's fired by YUI. So this YUI is client side, probably in My-tasks dashlet or my tasks page.
Furthermore, the error message looks like it is a status.message from the failed backend message/service.
You could probably locate that client-side javascript file, find the method that starts the task and see what its' failureCallback handler is. Then edit that failureCallback method and make it show something different then the response.status.message or whatever it is. Perhaps something like this.msg("message.my-custom-error-message"); which you then customize on your own.
Modifying YUI dialog scripts will might affect the other functionalities as well.
If we customize start-workflow. js, its only going to be achieved in start workflow form.
So as generic solution, below is the suggestion.
When alfresco is rendering the workflow form , it is rendering the transition button using the activiti-transition.js file.Basically this buttons are doing nothing more but submitting the workflow form.
So the best way would be , customizing this activiti-transition.ftl and activiti-transition.js file , to make an ajax call and handle the response as we want.
I just had a look on full flow of how this front end error is shown.
activiti-transition is submiting the workflow form.
Using a function named as submitForm which resides inside alfresco.js, it is invoking an submit event of form
Inside the forms-runtime.js file there is one function named as _submitInvoked(handles the submit event of form), which is responsible for making an ajax call and submitting the workflow form.If there is error while submitting , it will display the error which is from backend.
I am new for extjs.
I am having one store in which i am having some data coming from json file.
I have created a form.
i want to save new data in that store through form.
How can I create button and submit form on that button's click?
please let me know.
Thanks in advance
If you're using ExtJS 4 and your form is bound to a 'model' instance, then you get get a reference to your model in your buttons click handler and call:
model.save();
Which will send a post request to the url defined as the proxy on the model class.
Post your code and perhaps we can be some more direct help.
In the API of ExtJS is a good example on how to create a Ext.form.Panel with a button. When you click on this button the form gets submitted.
This example doesn't work because it doesn't submit to a page but it is very configurable.
Snippet of the button+handler:
buttons: [{
text: 'Submit',
handler: function() {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
url: '', //this is the url where the form gets submitted
success: function(form, action) {
Ext.Msg.alert('Success', action.result.msg);
},
failure: function(form, action) {
Ext.Msg.alert('Failed', action.result.msg);
}
});
}
}
}]
I am a jQuery newbie and ma trying to use a modal to reveal a constant contact simple form generated by the form generator. I have applied jQuery.validate(), and the validation is working, but I don't know how to submit the form. If there is an action="signup/index.php" in the tag, i land on a new page.
The generated form uses action='signup/index.php' and this file calls for a new page location see file in Github. I commented those last lines out, but still am failing to make the form submit. I cannot see the new email in the Constant Contact email list.
This is my sumbmit handler
submitHandler: function() {
$('#signup').click(function(e) {
$.post('signup/index.php', $().serialize(), function(data) {
$('#output-div').html(data);
});
$('#form-message').fadeIn(300, function() {
$('#form-message').html('<p>Thank you for joining our list. Great offers coming soon.</p>')
});
$('#myModal').delay(1500).trigger('reveal:close');
});
}
solved it.
I had commented out the last several lines of the signup/index.php, including this line
if($postFields['request_type'] == 'ajax'){ $postFields["success_url"]=''; $postFields["failure_url"]=''; }
For some reason, that line is needed for form submittal success. Everything after that line is commented out, from
if ($return_code==201) {
to
</ol>
</p>'; }
}
and my jQuery is handling messages, errors and completion as such
submitHandler: function() {
$.post('/dev/rest/ccphp/signup/index.php', $("#ccsfg").serialize(), function(data) {
$('#results').html(data);
}).success(function() {
$('#ccsfg').html('<h4>Thank you for joining our list. Great offers coming soon.</h4>');
})
.error(function() {
$('#ccsfg').html('<h4>Oops! There was an error. Please try again. </h4>');
})
.complete(function() {
$('#myModal').delay(1500).trigger('reveal:close');
});
}