|
| 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