gform/phone/countries

Introduction

The gform/phone/countries filter allows you to customize the countries list displayed in the international phone field. This filter provides access to the countries array before the phone field is initialized, enabling you to filter which countries appear in the dropdown, reorder them to prioritize specific regions, or combine both approaches.

Parameters

NameTypeDescription
dataobjectAn object containing the countries array and form/field context.
data.countriesarrayArray of country objects, each with properties like iso2, name, and dialCode.
data.formIdnumberThe ID of the form containing the phone field.
data.fieldIdnumberThe ID of the phone field being filtered.

Examples

Filter Countries.

The example below shows how to limit the countries list to only show the United States, Canada, and Mexico. This approach filters the existing countries array to include only the specified country codes.

gform.utils.addFilter( 'gform/phone/countries', function( data ) {
    var allowedCountries = [ 'us', 'ca', 'mx' ];
    data.countries = data.countries.filter( function( country ) {
        return allowedCountries.indexOf( country.iso2 ) !== -1;
    } );
    return data;
} );

Reorder Countries.

The example below demonstrates how to prioritize specific countries at the top of the list while maintaining all other countries below. In this case, Mexico, Canada, and the United States appear first in that specific order, followed by all remaining countries in their default order.

gform.utils.addFilter( 'gform/phone/countries', function( data ) {
    var priorityCountries = [ 'mx', 'ca', 'us' ];
    var priority = [];
    var rest = [];

    data.countries.forEach( function( country ) {
        if ( priorityCountries.indexOf( country.iso2 ) !== -1 ) {
            priority.push( country );
        } else {
            rest.push( country );
        }
    } );

    // Make priority countries have the same order as in the priorityCountries array
    priority.sort( function( a, b ) {
        return priorityCountries.indexOf( a.iso2 ) - priorityCountries.indexOf( b.iso2 );
    } );

    data.countries = priority.concat( rest );
    return data;
} );

Placement

Reference the article Adding JavaScript Code to the Frontend of Your Site.

Source Code

This filter is located in assets/js/src/theme/fields/international-phone/core/model.js

Since

This filter was added in Gravity Forms 3.0.0