Prevent Duplicate Selections

Prevent duplicate selections in choice-based fields. Currently works with Checkbox, Radio Button, Drop Down and Enhanced-UI-enabled Multi Select fields.

Instructions

  1. Install this snippet. https://gravitywiz.com/documentation/how-do-i-install-a-snippet/

  2. Add one of the following CSS classes to your fields:

    Global group (all fields interact together): gw-prevent-duplicates

    OR grouped mode (fields only interact within same group): gw-prevent-duplicates-1 gw-prevent-duplicates-2 gw-prevent-duplicates-teamA gw-prevent-duplicates-anything

    Any CSS class beginning with: gw-prevent-duplicates will be treated as its own independent duplicate-prevention group.

Example: gw-prevent-duplicates-1 -> fields only prevent duplicates within group 1 gw-prevent-duplicates-2 -> fields only prevent duplicates within group 2

Code

Filename: gw-prevent-duplicate-selections.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php
/**
 * Gravity Wiz // Gravity Forms // Prevent Duplicate Selections
 * https://gravitywiz.com/
 *
 * Prevent duplicate selections in choice-based fields. Currently works with Checkbox, Radio Button, Drop Down and
 * Enhanced-UI-enabled Multi Select fields.
 * Also supports multiple independent duplicate-prevention groups.
 *
 * Instructions:
 *
 * 1. Install this snippet.
 *    https://gravitywiz.com/documentation/how-do-i-install-a-snippet/
 *
 * 2. Add one of the following CSS classes to your fields:
 *
 *    Global group (all fields interact together):
 *    gw-prevent-duplicates
 *
 *    OR grouped mode (fields only interact within same group):
 *    gw-prevent-duplicates-1
 *    gw-prevent-duplicates-2
 *    gw-prevent-duplicates-teamA
 *    gw-prevent-duplicates-anything
 *
 *    Any CSS class beginning with:
 *    gw-prevent-duplicates
 *    will be treated as its own independent duplicate-prevention group.
 *
 * Example:
 *    gw-prevent-duplicates-1 -> fields only prevent duplicates within group 1
 *    gw-prevent-duplicates-2 -> fields only prevent duplicates within group 2
 *
 * Plugin Name:  Gravity Forms Prevent Duplicate Selections
 * Plugin URI:   https://gravitywiz.com/
 * Description:  Prevent duplicate selections in choice-based fields. Currently works with Checkbox, Radio Button, Drop Down and Enhanced-UI-enabled Multi Select fields.
 * Author:       Gravity Wiz
 * Version:      0.2
 * Author URI:   https://gravitywiz.com
 */

class GW_Prevent_Duplicate_Selections {
	public function __construct() {
		// do version check in the init to make sure if GF is going to be loaded, it is already loaded
		add_action( 'init', array( $this, 'init' ) );
	}

	public function init() {
		add_filter( 'gform_pre_render', array( $this, 'load_form_script' ), 10, 2 );
		add_action( 'gform_register_init_scripts', array( $this, 'add_init_script' ), 10, 2 );
	}

	public function load_form_script( $form, $is_ajax_enabled ) {

		if ( $this->is_applicable_form( $form ) && ! has_action( 'wp_footer', array( $this, 'output_script' ) ) ) {
			add_action( 'wp_footer', array( $this, 'output_script' ) );
			add_action( 'gform_preview_footer', array( $this, 'output_script' ) );
		}

		return $form;
	}

	public function add_init_script( $form ) {
		if ( ! $this->is_applicable_form( $form ) ) {
			return;
		}

		$script = 'new ' . __CLASS__ . '();';
		$slug   = implode( '_', array( strtolower( __CLASS__ ) ) );

		GFFormDisplay::add_init_script( $form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
	}

	public function output_script() {
		?>

		<script type="text/javascript">
		window.<?php echo __CLASS__; ?> = function() {

			var $ = jQuery;
			const gpadvsPreviousValues = {};

			window.gform.addFilter('gplc_excluded_input_selectors', function(selectors) {
				selectors.push('.gw-disable-duplicates-disabled');
				return selectors;
			});

			function getDuplicateGroups() {

				let groups = [];

				$('[class*="gw-prevent-duplicates"]').each(function() {

					let classes = this.className.split(/\s+/);

					classes.forEach(function(cls) {
						if (cls.indexOf('gw-prevent-duplicates') === 0 && groups.indexOf(cls) === -1) {
							groups.push(cls);
						}
					});
				});

				return groups;
			}

			function initGroups() {

				getDuplicateGroups().forEach(function(groupClass) {

					let $groupWrapper = $('.' + groupClass);

					$groupWrapper.on('change', 'input, select', function(event, selected) {

						gwDisableDuplicates(
							$(this),
							$groupWrapper.find('input, select'),
							selected
						);
					});

					let $inputs = $groupWrapper.find('input, select');

					$inputs.each(function() {
						gwDisableDuplicates(
							$(this),
							$inputs.not('.gw-disable-duplicates-disabled')
						);
					});
				});
			}

			function getChangedOptionElFromSelect($select, selected) {

				if (selected) {
					let value = selected.selected ? selected.selected : selected.deselected;
					return findOptionByValue($select, value);
				}

				if ($select.siblings('.ts-wrapper').length) {

					const val = $select.val();

					if (typeof val === 'string') {
						return findOptionByValue($select, val);
					}

					const selectId = $select.attr('id');
					const prevVal = gpadvsPreviousValues[selectId] || null;
					gpadvsPreviousValues[selectId] = val;

					let changedOptVal;

					if (!prevVal) {
						changedOptVal = val[0];
					} else if (prevVal.length > val.length) {
						changedOptVal = getArrayDiff(prevVal, val);
					} else {
						changedOptVal = getArrayDiff(val, prevVal);
					}

					return findOptionByValue($select, changedOptVal);
				}

				return $select.find('option:selected');
			}

			function getArrayDiff(arr1, arr2) {
				return arr1.filter(x => !arr2.includes(x))[0];
			}

			function findOptionByValue($select, value) {
				return $select.find('[value="' + value + '"]');
			}

			function gwDisableDuplicates($elem, $group, selected) {

				let $parent = $elem;

				if ($elem.is('select')) {
					$elem = getChangedOptionElFromSelect($elem, selected);
					$group = $group.find('option');
				}

				let value     = $elem.val();
				let $targets  = $group.not($elem).not('.gplc-disabled').not('.gpi-disabled').not('.gf_placeholder');
				let isChecked = $elem.is(':checked');

				let disabledClass = 'gf-default-disabled gw-disable-duplicates-disabled';
				let previousValue;

				if ($elem.is(':radio, option') && !$parent.prop('multiple')) {

					previousValue = $elem.parents('.gfield').data('previous-value');
					$elem.parents('.gfield').data('previous-value', $elem.val());

					if (previousValue) {
						$targets
							.filter('[value="{0}"]'.gformFormat(previousValue))
							.prop('disabled', false)
							.removeClass(disabledClass);
					}
				}

				let $filteredTargets = $targets
					.filter('[value="{0}"]'.gformFormat(value))
					.prop('disabled', isChecked);

				if ($elem.is('option')) {

					$filteredTargets.parents('select').each(function() {

						let $options = $(this).find('option');

						if ($options.filter(':selected:disabled').length) {
							$options.not(':disabled').first().prop('selected', true);
						}

						$(this).trigger('chosen:updated');
					});
				}

				if (isChecked) {
					$filteredTargets.addClass(disabledClass);
				} else {
					$filteredTargets.removeClass(disabledClass);
				}
			}

			initGroups();
		};
		</script>

		<?php
	}

	public function is_applicable_form( $form ) {
		foreach ( $form['fields'] as $field ) {
			if ( isset( $field->cssClass ) && str_contains( $field->cssClass, 'gw-prevent-duplicates' ) ) {
				return true;
			}
		}

		return false;
	}

}

# Configuration
new GW_Prevent_Duplicate_Selections();

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.