Skip to content

Commit 25ab6f2

Browse files
authored
gw-require-unique-values.php: Added support for whole-field validation for multi-input fields.
1 parent d6e5edf commit 25ab6f2

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

gravity-forms/gw-require-unique-values.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
* Plugin URI: https://gravitywiz.com/gravity-forms-require-unique-values-for-different-fields/
1212
* Description: Require two or more fields on the same form to be different from each other.
1313
* Author: Gravity Wiz
14-
* Version: 0.2
14+
* Version: 0.3
1515
* Author URI: https://gravitywiz.com/
1616
*/
1717
class GW_Require_Unique_Values {
@@ -52,6 +52,10 @@ public function init() {
5252
add_filter( sprintf( 'gform_field_validation_%s', $this->_args['form_id'] ), array( $this, 'validate' ), 10, 4 );
5353
}
5454

55+
private function get_all_field_ids() {
56+
return array_merge( $this->_args['field_ids'], array( $this->_args['master_field_id'] ) );
57+
}
58+
5559
public function validate( $result, $value, $form, $field ) {
5660

5761
if ( ! $this->is_applicable_field( $field ) ) {
@@ -83,8 +87,12 @@ public function validate( $result, $value, $form, $field ) {
8387
} else {
8488
$values = $this->get_group_values( $form, $field->id );
8589

90+
// Check if this should be validated as whole field
91+
$all_field_ids = $this->get_all_field_ids();
92+
$validate_as_whole = in_array( $field->id, $all_field_ids );
93+
8694
// If the field has inputs, let's loop through them and check if they are unique.
87-
if ( is_array( $field->inputs ) && ! empty( $field->inputs ) ) {
95+
if ( is_array( $field->inputs ) && ! empty( $field->inputs ) && ! $validate_as_whole ) {
8896
$is_unique = true;
8997

9098
foreach ( $field->inputs as $input ) {
@@ -194,6 +202,21 @@ public function get_filtered_value( $field, $input_id = null ) {
194202
$value = $value[ $input_id ];
195203
}
196204

205+
// When using a field ID (not input ID) for multi-input fields, combine all subfield values into one for validation.
206+
if ( ! $input_id && is_array( $field->inputs ) && is_array( $value ) ) {
207+
$all_field_ids = $this->get_all_field_ids();
208+
if ( in_array( $field->id, $all_field_ids ) ) {
209+
$combined_parts = array();
210+
foreach ( $field->inputs as $input ) {
211+
$input_value = rgar( $value, $input['id'] );
212+
if ( ! empty( $input_value ) ) {
213+
$combined_parts[] = $input_value;
214+
}
215+
}
216+
$value = array( implode( ' ', $combined_parts ) );
217+
}
218+
}
219+
197220
$value = ! is_array( $value ) ? array( $value ) : $value;
198221
$value = array_filter( $value );
199222

0 commit comments

Comments
 (0)