gform_geolocation_autocomplete_options_pre_init

Description

Allows customization of the options used to initialize the autocomplete for the address field.

Usage

gform.addFilter( 'gform_geolocation_autocomplete_options_pre_init', function ( options, formId, fieldId, address ) {
	return options;
} );

Parameters

  • options object
    The autocomplete options. The supported options can be found here.
  • formId number
    The ID of the form the address field belongs to.
  • fieldId number
    The ID of the address field autocomplete is to be initialized for.
  • address Element
    The Address field element.

Examples

Limit the available choices to a specific country (Great Britain) in Form ID 1 and Field ID 2.

gform.addFilter( 'gform_geolocation_autocomplete_options_pre_init', function ( options, formId, fieldId, address ) {
	if ( formId == 1 && fieldId == 2 ) {
		options.componentRestrictions = { country: 'GB' };
	}
	return options;
} );

Add a data attribute to the field markup containing the country code related to the address type selected in the field settings.

Use gform_field_container filter to add the data attribute (PHP).

add_filter( 'gform_field_container', function ( $field_container, $field ) {
	if ( ! $field instanceof GF_Field_Address|| empty( $field->ggeolocationEnableGeolocationSuggestions ) ) {
		return $field_container;
	}

	$type        = empty( $field->addressType ) ? $field->get_default_address_type( $field->formId ) : $field->addressType;
	$type_config = rgar( $field->get_address_types( $field->formId ), $type );
	if ( empty( $type_config ) ) {
		return $field_container;
	}

	$hide_country = ! empty( $type_config['country'] ) || $field->hideCountry || $field->get_input_property( 6, 'isHidden' );
	if ( ! $hide_country ) {
		return $field_container;
	}

	$code = $field->get_country_code( rgar( $type_config, 'country', $field->defaultCountry ) );
	if ( empty( $code ) ) {
		return $field_container;
	}

	return str_replace( 'data-js', sprintf( "data-country-code='%s' data-js", esc_attr( $code ) ), $field_container );
}, 11, 2 );

Now you can access the attribute with gform_geolocation_autocomplete_options_pre_init (JS):

gform.addFilter( 'gform_geolocation_autocomplete_options_pre_init', function ( options, formId, fieldId, address ) {
	if ( address.dataset?.countryCode ) {
		options.componentRestrictions = { country: address.dataset.countryCode };
	}
	return options;
} );

Placement

Your code snippet can be placed in an HTML field on your form or in a theme custom JavaScript file.

See also the JavaScript/jQuery section in this article: Where Do I Put This Code?

Source Code

This filter is located in enableAutocomplete() in google-places.js.

Since

Geolocation 1.3.0