How to Convert String to ID in Salesforce Apex

While working on a Salesforce development project, I was debugging an Apex class that was supposed to update an account record based on its ID, but I kept encountering an “Invalid ID” error.

Then, I tested and validated a string conversion to an ID type in the developer console to ensure the conversion logic worked correctly. There, I used the function Id.valueOf(strId) and was able to convert the string to Id.

In this Salesforce tutorial, I will explain how to convert a string data type to an ID value in Salesforce Apex.

Convert String to ID in Salesforce Apex

To convert the string to ID in Salesforce Apex, navigate to the developer console and follow the steps below.

  1. Create an Apex class in the developer console, and for that, click on File > New > Apex Class.
  1. Enter the name for the apex class and click OK.
Convert String to Id in Salesforce Apex
  1. Enter the code below in the developer and save the code.
public class ConvertStringToId {
    public static Id convertStringToId(String strId) {
        Id convertedId;
        convertedId = Id.valueOf(strId); 
      
        return convertedId;
    }
}
  • ConvertStringToId.Id: This shows that the method will return an ID-type value from the string.
  • (String strId): The method takes one input parameter named str Id of type String.
  • Id.valueOf(strId): This is a built-in method provided by Salesforce that converts a String to an Id type. If the provided string is not a valid Salesforce ID format (e.g., not 15 or 18 characters long), it will throw a System.StringException.
  • Return convertedId: It will return the converted Id.
  1. After entering and saving the code, if there are no errors, then press ” Ctrl + E” to execute the code.
  1. In the anonymous window, enter the code below, then select the checkbox, open in Log, and click the Execute button.
String accountIdString = '0015i00000lU1htAAC';
Id resultId = ConvertStringToId.convertStringToId(accountIdString);
System.debug('Resulting Id: ' + resultId);

Here, “Id resultId” will call the method from the class to convert the string to Id.

How to convert a string to Id in Salesforce apex
  1. In the debug console, select the checkbox to debug only. Then, you will see that the entered string ID is returned as ID.

This way, we can convert a string to an ID in Salesforce Apex by using the function ID.valueOf (strID) in the Apex class.

Convert a List String to Set of IDs in Salesforce Apex

In the above method, we converted a single string to an ID, but we can also convert a batch of record data from a string to an ID in Salesforce Apex.

In the steps below, I will explain how to convert a list of strings to a set of IDs in Salesforce Apex.

Now, n