Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active February 22, 2022 08:38
Show Gist options
  • Save wpmudev-sls/9917696b87543e3edb92e84f41933be0 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/9917696b87543e3edb92e84f41933be0 to your computer and use it in GitHub Desktop.
[Forminator] - Store Fields In Cookie. Useful for huge forms with several pages, so member can come back later and continue from where he stopped
<?php
/**
* Plugin Name: [Forminator] - Store Fields In Cookie
* Plugin URI: https://premium.wpmudev.org/
* Description: Useful for huge forms with several pages, so member can come back later and continue from where he stopped
* Author: Panos Lyrakis @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
add_action(
'wp_footer',
function() {
/**
* This is an array of form ids that will apply this script
* In order to make it applicable for all forms you can leave the array empty:
* $allowed_form_ids = array();
*/
$allowed_form_ids = array( 6, 11, 12, 345, 6434 );
/**
* Accepted values can be
* "button" : With button, the script will store form's inputs in cookies when then Next/Previous buttons are clicked
* "focusout" : With focusout, the script will store only the
*/
// $store_trigger = 'button'; // OR 'focusout'
$store_trigger = 'focusout'; // OR 'button'
global $post;
if ( ! $post instanceof WP_Post || ! has_shortcode( $post->post_content, 'forminator_form' ) ) {
return;
}
?>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
(($,d)=>{
if ( window.wpmudev_forminator_saved_fields ) {
return;
}
window.wpmudev_forminator_saved_fields = {
cform_ajax_action : 'forminator_load_cform',
cookie_name : 'wpmudev_forminator_saved_fields',
cookie_expire_days : 15,
saved_fields : [],
allowed_form_ids : <?php echo json_encode( $allowed_form_ids ); ?>,
store_trigger : '<?php echo $store_trigger; ?>',
path : window.location.pathname,
excluded_fields : [ 'forminator_nonce' ],
init : function() {
$(d).ajaxComplete( function( event, xhr, settings ) {
let _this = wpmudev_forminator_saved_fields,
action = _this.get_query_var( 'action', settings.data );
if ( action === _this.cform_ajax_action ) {
_this.load_cookie_values();
}
});
this.load_cookie_values();
if ( 'button' === this.store_trigger ) {
$( d ).on( 'click', '.forminator-button', wpmudev_forminator_saved_fields.record_fields );
} else {
$( d ).on( 'focusout', '.forminator-custom-form input, .forminator-custom-form select, .forminator-custom-form textarea', wpmudev_forminator_saved_fields.record_fields );
}
},
load_cookie_values : function() {
const forms = $( 'form.forminator-custom-form' );
forms.each( this.fill_in_form );
},
fill_in_form : function() {
let _this = wpmudev_forminator_saved_fields,
form_id = $(this).attr( 'id' ),
_form_id = form_id.replace( 'forminator-module-', '' ),
form_cookie = wpmudev_forminator_saved_fields.get_cookie( form_id ),
form_fields;
if ( form_cookie != null ) {
form_fields = form_cookie.split('&');
$.each( form_fields, function( k, v ) {
let field = v.split('='),
value = decodeURIComponent( field[1] );
// Let's skip nonce
if ( _this.excluded_fields.includes( field[0] ) ) {
return;
}
if ( field[0].startsWith( 'radio' ) || field[0].startsWith( 'checkbox' ) ) {
$(`#${form_id} [name="${field[0]}"]`).filter(`[value="${value}"]`).prop( 'checked', true );
}else if ( field[0].startsWith( 'select' ) ) {
// For Select fields we need to trigger `fui:change`
$( `#${form_id} [name="${field[0]}"]` ).val( value ).trigger('fui:change');
}else {
// For another fields
$( `#${form_id} [name="${field[0]}"]` ).val( value ).trigger('change');
}
});
}
if ( _this.allowed_form_ids.length !== 0 && ! _this.in_json( _form_id, _this.allowed_form_ids ) ) {
return;
}
/*
if ( form_cookie ) {
let cookie_json = JSON.parse( `[${form_cookie}]` ),
form_json = cookie_json[0];
Object.keys( form_json ).forEach( function( key ) {
let field = $( `#${form_id} #${key}` );
if ( '' != form_json[key] ) {
field.val( form_json[key] );
}
});
}
*/
},
record_fields : function() {
let _this = wpmudev_forminator_saved_fields,
form_id = $( this ).closest( 'form' ).attr( 'id' ),
form = $( `#${form_id}` );
_this.set_cookie( form_id, _this.serialize( form ) );
$(document).on( 'response.success.load.forminator', wpmudev_forminator_saved_fields.delete_cookie.run );
form.on( 'submit', function(){
let _this = wpmudev_forminator_saved_fields
_this.delete_cookie( $( this ).attr( 'id' ) );
} );
},
get_cookie : function( form_id ) {
let _this = wpmudev_forminator_saved_fields,
name = _this.cookie_name + '_' + form_id + "=",
ca = document.cookie.split(';');
for( var i = 0; i < ca.length; i++ ) {
var c = ca[i];
while ( c.charAt(0) == ' ' ) {
c = c.substring(1);
}
if ( c.indexOf( name ) == 0 ) {
return c.substring( name.length, c.length );
}
}
return "";
},
set_cookie: function( form_id, cvalue ) {
let _this = wpmudev_forminator_saved_fields,
current_date = new Date(),
cookie_name = _this.cookie_name + '_' + form_id,
expires = '';
current_date.setTime( current_date.getTime() + ( _this.cookie_expire_days * 24 * 60 * 60 * 1000 ) );
expires = `expires=${current_date.toUTCString()}`;
d.cookie = `${cookie_name}=${cvalue}; ${expires} ;path=${_this.path};`;
},
delete_cookie: function( form_id ) {
let _this = wpmudev_forminator_saved_fields,
cookie_name = _this.cookie_name + '_' + form_id;
d.cookie = `${cookie_name}=; max-age=0; path=${_this.path}; expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
},
serialize: function( form ){
return $.map( form.serializeArray(), function(val) {
return [val.name, encodeURIComponent(val.value)].join('=');
}).join('&');
},
in_json: function( needle, haystack ) {
var length = haystack.length;
for( var i = 0; i < length; i++ ) {
if( haystack[i] == needle ) {
return true;
}
}
return false;
},
get_query_var: function( name, url ) {
if ( ! url ) {
return false;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp(name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return false;
if (!results[2]) return false;
return decodeURIComponent( results[2].replace(/\+/g, " ") );
}
};
$( d ).ready( function(){
wpmudev_forminator_saved_fields.init();
} );
})(jQuery,document);
});
</script>
<?php
},
20
);
@askags
Copy link

askags commented Jun 30, 2020

Can you put another feature where user can define the form ids for which the submit button should remove cookies.

@Mr-GipsyKing
Copy link

Could you make an WPForms version ? :)

@askags
Copy link

askags commented Jan 12, 2021

Hi!

I have been using this work-around since quite a long time.

However, after recent update in forminator, this plugin has stopped working and the cookies are no longer storing anything.

Can you please check once from your end?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment