A Handy Method For Converting 15 Character ID Strings In Salesforce to 18 Characters
The way Salesforce.com generates its IDs with 15 and 18 character versions may work well for certain things, but it can cause developers headaches when trying to use them in Apex. When trying to compare ID’s as strings in Apex, we often end up comparing the 15 character ID to the 18 character ID and don’t receive a match.
Here is Salesforce’s explanation of why there are two ID lengths and how they are used:
There are two versions of each record ID: a 15 digit case-sensitive version which is referenced in the UI, and an 18 digit case-insensitive version which is referenced through the API. The last 3 digits of the 18 digit ID are a checksum of the capitalizations of the first 15 characters. This ID length was created as a workaround to legacy systems which were not compatible with case-sensitive IDs. The API will accept the 15 digit ID as input, but will always return the 18 digit ID.
To get around this issue, we created an Apex method that was based on Ron Hess’s example (that he posted on the forums) to address displaying the 18 character ID in an S-Control found here. If you need to do string comparisons of Salesforce ID’s, or you just need the 18 character version of the ID for some other reason, we hope you will find this method useful.
public string generate18CharId(string id){
// This method will take a 15 character ID and return its 18 character ID:
if (id == null){
return null;
}
if (id.length() != 15) {
return null;
}
string suffix = '';
integer flags;
for (integer i = 0; i < 3; i++) {
flags = 0;
for (integer j = 0; j < 5; j++) {
string c = id.substring(i * 5 + j,i * 5 + j + 1);
//Only add to flags if c is an uppercase letter:
if (c.toUpperCase().equals(c) && c >= 'A' && c <= 'Z') {
flags = flags + (1 << j);
}
}
if (flags <= 25) {
suffix = suffix + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
}else{
suffix = suffix + '012345'.substring(flags-25,flags-24);
}
}
return id + suffix;
}

Comments
Be the first to comment!
Leave A Comment