Dynamically toggle field as required based on control field value

Instructions

Code

Filename: gw-dynamic-required-fields.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
<?php
/**
 * Gravity Wiz // Gravity Forms // Dynamically toggle field as required based on control field value
 * https://gravitywiz.com/
 *
 * Instruction Video: https://www.loom.com/share/d7499c8ae2924477ab9fbe5ef5be7c07
 *
 * Instructions:
 *
 * 1. Install the snippet.
 *    https://gravitywiz.com/documentation/how-do-i-install-a-snippet/
 */
class GW_Dynamic_Required_Fields {

	public static $instances = array();

	public static function init( $args ) {
		$required_keys = array( 'form_id', 'control_field', 'rules' );

		foreach ( $required_keys as $key ) {
			if ( ! isset( $args[ $key ] ) ) {
				return new WP_Error( 'missing_parameter', "Missing required parameter: {$key}" );
			}
		}

		$instance          = new self( $args );
		self::$instances[] = $instance;

		return $instance;
	}

	private $args = array();

	public function __construct( $args ) {
		$this->args = wp_parse_args(
			$args,
			array(
				'form_id'       => false,
				'control_field' => false,
				'rules'         => array(),
				'field_labels'  => array(),
			)
		);

		$form_id = $this->args['form_id'];

		add_filter( "gform_pre_validation_{$form_id}", array( $this, 'validate_dynamic_fields' ) );
		add_filter( "gform_pre_submission_{$form_id}", array( $this, 'validate_dynamic_fields' ) );

		add_filter( 'gform_register_init_scripts', array( $this, 'add_init_script' ), 10, 2 );
	}

	/**
	 * Validate dynamic fields based on control field value.
	 *
	 * @param array $form The form object.
	 *
	 * @return array Modified form object.
	 */
	public function validate_dynamic_fields( $form ) {
		$control_value   = rgpost( 'input_' . $this->args['control_field'] );
		$required_fields = $this->get_required_fields( $control_value );

		foreach ( $form['fields'] as &$field ) {
			if ( in_array( $field->id, $required_fields, true ) ) {
				$field->isRequired = true;

				$value = rgpost( 'input_' . $field->id );
				if ( GFCommon::is_empty_array( $value ) ) {
					$field->failed_validation  = true;
					$field->validation_message = $this->get_field_label( $field->id ) . ' is required';
				}
			} else {
				$field->isRequired = false;
			}
		}

		return $form;
	}

	/**
	 * Add initialization script for dynamic field requirements.
	 *
	 * @param array $form    The form object.
	 * @param bool  $is_ajax Whether the form is being submitted via AJAX.
	 */
	public function add_init_script( $form, $is_ajax ) {
		if ( $form['id'] !== $this->args['form_id'] ) {
			return;
		}

		$script = $this->get_js();
		$slug   = "gw_dynamic_required_{$form['id']}";

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

	/**
	 * Get required fields based on control value.
	 *
	 * @param string $control_value The value of the control field.
	 *
	 * @return array Array of required field IDs.
	 */
	private function get_required_fields( $control_value ) {
		foreach ( $this->args['rules'] as $rule ) {
			if ( $rule['value'] === $control_value ) {
				return $rule['field_ids'];
			}
		}

		return array();
	}

	/**
	 * Get field label for validation message.
	 *
	 * @param int $field_id The field ID.
	 *
	 * @return string The field label.
	 */
	private function get_field_label( $field_id ) {
		if ( isset( $this->args['field_labels'][ $field_id ] ) ) {
			return $this->args['field_labels'][ $field_id ];
		}

		return "Field {$field_id}";
	}

	/**
	 * Generate JavaScript for dynamic field requirements.
	 *
	 * @return string JavaScript code.
	 */
	private function get_js() {
		$form_id  = $this->args['form_id'];
		$control  = $this->args['control_field'];
		$rules_js = array();
		$all_ids  = array();

		foreach ( $this->args['rules'] as $rule ) {
			$rules_js[ $rule['value'] ] = $rule['field_ids'];
			$all_ids                    = array_merge( $all_ids, $rule['field_ids'] );
		}

		$all_ids = array_unique( $all_ids );

		ob_start();
		?>
		(function($) {
			var formId = <?php echo intval( $form_id ); ?>;
			var controlId = <?php echo intval( $control ); ?>;
			var rules = <?php echo wp_json_encode( $rules_js ); ?>;
			var allIds = <?php echo wp_json_encode( $all_ids ); ?>;

			function updateRequirements() {
				var value = $('#input_' + formId + '_' + controlId).val();
				var requiredIds = rules[value] || [];

				allIds.forEach(function(id) {
					var isRequired = requiredIds.includes(id);
					var $field = $('#field_' + formId + '_' + id);
					var $input = $('#input_' + formId + '_' + id);

					if (isRequired) {
						$field.addClass('gfield_contains_required');
						$input.attr('aria-required', 'true');
						if (!$field.find('.gfield_required').length) {
							$field.find('.gfield_label').append('<span class="gfield_required">*</span>');
						}
					} else {
						$field.removeClass('gfield_contains_required');
						$input.attr('aria-required', 'false');
						$field.find('.gfield_required').remove();
						$field.removeClass('gfield_error').find('.validation_message').remove();
					}
				});
			}

			$('#input_' + formId + '_' + controlId).on('change', updateRequirements);
			$(document).on('gform_post_render', updateRequirements);
			$(document).ready(updateRequirements);

		})(jQuery);
		<?php
		return ob_get_clean();
	}
}

# Configuration

new GW_Dynamic_Required_Fields(
	array(
		'form_id'       => 3,
		'control_field' => 1,
		'rules'         => array(
			array(
				'value'     => 'Both Compulsory',
				'field_ids' => array( 2, 3 ),
			),
			array(
				'value'     => 'One Compulsory',
				'field_ids' => array( 2 ),
			),
			array(
				'value'     => 'No Compulsory',
				'field_ids' => array(),
			),
		),
	)
);

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.