Skip to content

Commit 54152c4

Browse files
committed
Initial commit
0 parents  commit 54152c4

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Changelog
2+
3+
## 1.0 / 2018-10-25
4+
5+
- Initial release

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Gravity Forms JavScript Dynamic Population
2+
3+
Some caching systems ignore query parameters, preventing Gravity Forms from dynamically populating field values.
4+
5+
This plugin bypasses that problem by filling Gravity Forms fields that have dynamic population enabled on the client side using JavaScript.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
<?php
3+
/*
4+
Plugin Name: Gravity Forms JavaScript Dynamic Population
5+
Plugin URI: https://github.com/mmirus/gravity-forms-javascript-dynamic-population
6+
Author: Matt Mirus
7+
Author URI: https://github.com/mmirus
8+
Version: 1.0
9+
GitHub Plugin URI: https://github.com/mmirus/gravity-forms-javascript-dynamic-population
10+
*/
11+
12+
// add data-prefill attribute to fields
13+
add_filter('gform_field_content', function ($field_content, $field, $value, $entry_id, $form_id) {
14+
if (!$field->allowsPrepopulate) return $field_content;
15+
return str_replace('name=', "data-prefill='{$field->inputName}' name=", $field_content);
16+
}, 10, 5);
17+
18+
// fill values from query params for fields where dynamic population is enabled
19+
add_action('gform_register_init_scripts', function ($form) {
20+
$script = "
21+
const getUrlParameter = function(name) {
22+
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
23+
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
24+
var results = regex.exec(location.search);
25+
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
26+
};
27+
const fields = [].slice.call(document.querySelectorAll('[data-prefill]'));
28+
fields.forEach(function(field) {
29+
const value = getUrlParameter(field.dataset.prefill);
30+
if (value === '') return;
31+
32+
const fieldType = (field.tagName === 'INPUT') ? field.type : field.tagName.toLowerCase();
33+
switch (fieldType) {
34+
case 'checkbox':
35+
case 'radio':
36+
field.checked = (value.split(',').indexOf(field.value) !== -1);
37+
break;
38+
case 'select':
39+
jQuery(field).val(value.split(','));
40+
break;
41+
default:
42+
field.value = value;
43+
}
44+
});
45+
";
46+
47+
GFFormDisplay::add_init_script($form['id'], 'populate_fields', GFFormDisplay::ON_PAGE_RENDER, $script);
48+
}, 10, 2);

0 commit comments

Comments
 (0)