0

Some of the phone numbers of Contacts are formatted as (123) 456-7891

I need to change the format of all phone numbers to 1234567891.

I don't want to create another formula field that contains the correct format. I want to change the format of all the current phone numbers(and future phone numbers) to the format 1234567891.

Do I need to create a batch Apex class for this? If so, how should I go about formatting the numbers? I couldn't find anything on google.

How should I proceed?

2 Answers 2

1

The Salesforce UI automatically formats numbers this way, so you'll want a trigger:

trigger FixNumbers on Contact (before insert, before update) {
  sObjectField[] phoneFields = new sObjectField[] {
    Contact.Phone, Contact.Fax, Contact.Mobile // Which fields to fix...
  };
  for(Contact record: Trigger.new) {
    for(sObjectField field: phoneFields) {
      String phoneNumber = (String)record.get(field);
      if(phoneNumber != null) {
        // regex remove all non-numbers
        record.put(field, phoneNumber.replaceAll('\\D','')); 
      }
    }
  }
}

To fix all existing records, you can either export/import via reports/data loader/import wizard/etc, or you can write Apex, if you want:

public class UpdateRecords implements Database.Batchable<sObject> {
  public Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator([SELECT Id FROM Contact]);
  }
  public void execute(Database.BatchableContext context, Contact[] records) {
    update records; // Trigger will do the work for us
  }
  public void finish(Database.BatchableContext context) {
  }
}
1
  • Thank you for your answer! I added the trigger to the sandbox and activated it. When I insert/update a record, the phone number gets updated to the correct format in list view. However, when I go to the contact record, the original incorrect format is displayed. Do you have any idea why this might be happening and if there is any way around it?
    – Aish
    Jun 8, 2022 at 12:20
2

In case you want to use E164 format - here's a utility method I wrote a while back. Adapt as required. YMMV

/** -----------------------------------------------------------------
*   toE164  : Normalizes phone number to E.164 format somestring.toE164(String countryCode)
*               Ideal solution would be an Apex port of Google libphonenumber but this is a huge library
*               We'll do simple stuff, stripping out noise characters, extensions and adding back the country code
*               Custom metadata
*               could be used but for batch performance, static maps for now.
*           If the number is not recognizable, unsupported country or too short, return asis.
*
*           Converts (650)555-1212 to +16505551212
*           Converts +44 (020) 88.99.11.22 to +442088991122
**/

private class NationalPhoneNature {
    String countryCode;
    Integer minLen;
    Integer maxLen;
    String trunkCode;
    
    NationalPhoneNature withCountryCode(String val) {this.countryCode = val; return this;} 
    NationalPhoneNature withMinLen(Integer val) {this.minLen = val; return this;} 
    NationalPhoneNature withMaxLen(Integer val) {this.maxLen = val; return this;} 
    NationalPhoneNature withTrunkCode(String val) {this.trunkCode = val; return this;} 
}
private static final Map<String,NationalPhoneNature> NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE = new Map<String,NationalPhoneNature> {
    'CA' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1'),
    'MX' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1'),
    'UK' => new NationalPhoneNature().withCountryCode('44').withMinLen(9).withMaxLen(10).withTrunkCode('0'),
    'US' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1')
};
    
public static String toE164(String phoneNum) {
    return toE164(phoneNum, 'US');
}    
public static String toE164(String phoneNum, String isoCountryCode) {
    if (phoneNum == null) return null;
    if (!NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE.containsKey(isoCountryCode)) return phoneNum; // not supported
    
    String phonePure = phoneNum.replaceAll('[^0-9]','');    // strip noise chars, leading +, etc.
    
    NationalPhoneNature nature = NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE.get(isoCountryCode);
    //  Strip off country code, if any
    if (phonePure.startsWith(nature.countryCode)) {
        phonePure = phonePure.substring(nature.countryCode.length());
    }
    //  Strip off trunk code, if any
    if (phonePure.startsWith(nature.trunkCode)) {
        phonePure = phonePure.substring(nature.trunkCode.length());
    }
        
    //  Check what we have left to see if workable
    if (phonePure.length() < nature.minLen) {
        return phoneNum;
    }
    
    //  If greater than max length, assume excess is an extension (not supported here)
    if (phonePure.length() > nature.maxLen) {
        phonePure = phonePure.substring(0,nature.maxLen);
    }
    
    return '+' + nature.countryCode + phonePure;
}
1
  • really nice piece of code!!
    – Maserick
    Jan 12 at 14:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .