Apply function to all phone fields

Hallo,

We have a function that should check phone number and to add country code at the begining. It is working good but we need to find a way so we can apply it to all phone fields on different forms.
On that way we won’t need to found out phone field ID for each form and to call function for each form separately. Here you can see our function. Thanks!

add_action( 'gform_pre_submission_10', 'code_phone' );
function code_phone( $form ) {
	$org_value =  $_POST['input_4'];
	if (substr($org_value, 0, 1) === '0') {
		$final_value = '+49' . substr($org_value, 1);
	}
	$_POST['input_4'] = $final_value;
}

You can check the $field['type'] in your code and apply it only to type == ‘phone’ fields. It would look something like this (untested):

add_action( 'gform_pre_submission_10', 'code_phone' );
function code_phone( $form ) {
	GFCommon::log_debug( __METHOD__ . '(): ORIGINAL POST' . print_r( $_POST, true ) );
	foreach ( $form['fields'] as $field ) {
		if ( $field['type'] == 'phone' ) {
			GFCommon::log_debug( __METHOD__ . '(): I found a phone number field!' . print_r( $field, true ) );
			$field = 'input_' . $field['id'];
			$org_value =  rgpost ( $field );
			GFCommon::log_debug( __METHOD__ . "(): Original value => {$org_value}." );
			if ( substr( $org_value, 0, 1 ) === '0' ) {
				GFCommon::log_debug( __METHOD__ . "(): Substring matches." );
				$final_value = '+49' . substr( $org_value, 1 );
				$_POST["{$field}"] = $final_value;
				GFCommon::log_debug( __METHOD__ . '(): Altered POST' . print_r( $_POST, true ) );
			}
		}
	}
}
1 Like

You’d also need to strip the _10 from the filter in order to apply this to all forms and not only form ID 10. Thus, the first line:

add_action( 'gform_pre_submission', 'code_phone' );
1 Like

Oh yeah, good point :slight_smile:

Thank you for your fast response. I just removed form ID and use it as it is. It worked perfect!

1 Like