Skip to content

Commit a36940a

Browse files
authored
gpapf-validation-only.php: Added new snippet.
1 parent 715c12b commit a36940a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
/**
3+
* Gravity Perks // Advanced Phone Field // Validation Only
4+
* https://gravitywiz.com/documentation/gravity-forms-advanced-phone-field/
5+
*
6+
* Use this snippet if you prefer GF's standard Phone field UX but would like to use GPAPF's real phone number validation.
7+
* This snippet will automatically apply to all Phone fields with the "standard" format (e.g. (###) ###-####) where GPAFP
8+
* is not enabled.
9+
*/
10+
add_action( 'init', function() {
11+
12+
/**
13+
* Enable GPAPF for all Phone fields during validation to allow GPAPF to handle validating the phone number's validity
14+
* without interfering with the Phone field's default UX.
15+
*/
16+
add_filter( 'gform_field_validation', function( $result, $value, $form, $field ) {
17+
if ( $field->get_input_type() === 'phone' && $field->phoneFormat === 'standard' && ! $field->gpapfEnable ) {
18+
$field->gpapfEnable = true;
19+
// GPAPF unsets the `phoneFormat` to avoid format-specific validation messages. We need to store the original
20+
// format and reset it after GPAFP's validation. Unfortunately, since we need GF to initialize its input mask
21+
// based on the `phoneFormat`, we have to allow it to output its format-specific validation message. Which we
22+
// remove via DOM manipulation below.
23+
$field->origPhoneFormat = $field->phoneFormat;
24+
}
25+
return $result;
26+
}, 9, 4 );
27+
28+
/**
29+
* Disable GPAPF after validation so that it does not interfere with the default Phone field's input mask.
30+
*/
31+
add_filter( 'gform_field_validation', function( $result, $value, $form, $field ) {
32+
if ( $field->origPhoneFormat ) {
33+
$field->gpapfEnable = false;
34+
$field->phoneFormat = $field->origPhoneFormat;
35+
}
36+
return $result;
37+
}, 11, 4 );
38+
39+
/**
40+
* Remove the format-specific validation message that is added by Gravity Forms when a Phone field is marked as having
41+
* failed validation. See the more detailed comment above the setting of the `origPhoneFormat` property above.
42+
*/
43+
add_filter( 'gform_field_content', function( $content, $field ) {
44+
45+
if ( $field->get_input_type() !== 'phone' || $field->phoneFormat !== 'standard' || $field->gpapfEnable ) {
46+
return $content;
47+
}
48+
49+
$dom = new DOMDocument();
50+
$dom->loadHTML( $content );
51+
52+
foreach ( $dom->getElementsByTagName( 'div' ) as $div ) {
53+
if ( strpos( $div->nodeValue, 'Phone format:' ) === 0 && in_array( 'instruction', explode( ' ', $div->getAttribute( 'class' ) ) ) ) {
54+
$div->parentNode->removeChild( $div );
55+
}
56+
}
57+
58+
return $dom->saveHTML();
59+
}, 10, 2 );
60+
61+
} );

0 commit comments

Comments
 (0)