I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg_code) which is a combination of submission date and a random number to make it unique.
So I added an hidden input field to my CF7 code with the id "reg_code". On my first try, I used JS to generate a "reg_code" variable right after users visit my site and set the hidden field value to the generated "reg_code" variable. The "reg_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg_code" would not be correct because that code was generated at his first visit time and cached in the browser.
To avoid this issue, I decided to move the "reg_code" generation function from JS to PHP and the procedure would be like this:
- Submit button clicked
- Use AJAX to call a PHP function which returns a reg_code
- Set the hidden field "reg_code" in CF7 value to the returned result
- Really perform CF7 submission which saves all CF7 fields to Flamingo
This is my JS to trigger the AJAX call before CF7 submit event:
$('.wpcf7-form').on('submit', function (e) {
$.ajax({
type: "post",
dataType: "json",
url: js_object.ajax_url,
data: {
action: "custom_reg_code",
},
success: function (response) {
if (response.success) {
$('#reg_code').val(response.data)
}
else {
console.log('Something wrong')
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('fail: ' + textStatus, errorThrown);
},
complete: function() {
}
})
})
My result: It works only some times. Only some submissions have "reg_code" value, some others have empty "reg_code".
As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add e.preventDefault() to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.
Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?
Thank you very much
I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg_code) which is a combination of submission date and a random number to make it unique.
So I added an hidden input field to my CF7 code with the id "reg_code". On my first try, I used JS to generate a "reg_code" variable right after users visit my site and set the hidden field value to the generated "reg_code" variable. The "reg_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg_code" would not be correct because that code was generated at his first visit time and cached in the browser.
To avoid this issue, I decided to move the "reg_code" generation function from JS to PHP and the procedure would be like this:
- Submit button clicked
- Use AJAX to call a PHP function which returns a reg_code
- Set the hidden field "reg_code" in CF7 value to the returned result
- Really perform CF7 submission which saves all CF7 fields to Flamingo
This is my JS to trigger the AJAX call before CF7 submit event:
$('.wpcf7-form').on('submit', function (e) {
$.ajax({
type: "post",
dataType: "json",
url: js_object.ajax_url,
data: {
action: "custom_reg_code",
},
success: function (response) {
if (response.success) {
$('#reg_code').val(response.data)
}
else {
console.log('Something wrong')
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('fail: ' + textStatus, errorThrown);
},
complete: function() {
}
})
})
My result: It works only some times. Only some submissions have "reg_code" value, some others have empty "reg_code".
As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add e.preventDefault() to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.
Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?
Thank you very much
Share Improve this question asked Jun 23, 2018 at 16:45 LocNguyenLocNguyen 531 gold badge1 silver badge6 bronze badges 2- Not sure if you get alerted on answer edits, so this is just to let you know I've added a method that should let you add your own CF7 tag without using the extra plugin. I've not tested it, but the code is pretty straightforward. – Andy Macaulay-Brook Commented Jun 23, 2018 at 20:40
- Can we use something semilar for automatic numbering of submissions, so every new submision gets +1 number? – Mitja Commented Feb 28, 2020 at 8:50
2 Answers
Reset to default 3You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.
Method 1, with the aid of a plugin
I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer.
With this plugin in place you can put tags into your CF7 form like this:
[dynamichidden custom-reg-code “CF7_custom_reg_code”]
And in the email pane of CF7's admin page you'd insert [custom-reg-code].
To get it working, just make yourself a matching shortcode to generate your string:
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_custom_reg_code() {
return date("Ymd") . generateRandomString();
}
add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');
Hat-tip to https://stackoverflow/a/13212994/6347850 for the random number generation.
Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field.
Method 2, without the aid of a plugin
And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin.
To create a CF7 tag [serial]
, you register it using wpcf7_add_form_tag()
on the wpcf7_init
action hook, passing the name of the tag and the name of a callback function to handle it:
add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );
function wpse306816_CF7_add_custom_tag() {
wpcf7_add_form_tag(
'serial',
'wpse306816_CF7_handle_custom_tag' );
}
And for your case, the callback simply needs to return the serial string value:
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_handle_custom_tag( $tag ) {
return date("Ymd") . generateRandomString();
}
I'd like to chime in here because I was just struggling with this same problem - modifying inputs before CF7 was submitted via ajax. I believe the original poster was trying to figure out how to do this via Javascript, which Andy did not address in his answer. So here is an example of how to do that:
var form = document.getElementsByClassName('wpcf7-form')[0];
form.addEventListener('submit', function(evt) {
form.elements['reg_code'].value = 'parsed_code';
}, { capture: true });
Pay close attention to last argument in the event listener - useCapture = true
. This argument is false by default. My original code, which didn’t work, ignored this argument. The CF7 Ajax submission would always fire first, thus ignoring my event. By simply changing useCapture to true, your event fires first before dispatching the CF7 Ajax event.
I haven’t tried it yet, but I assume by also using Tested 4/22/2019 - doesn’t work.evt.preventDefault()
, you could effectively stop the CF7 Ajax form from submitting if needed.