Skip to main content

Logic to convert 15-character id to 18-character id Salesforce

 As we all know, Salesforce supports both 15-character id and 18-character id. Before API version 2.0, Salesforce supported only Case sensitive id. From API version 2.0 and higher, Salesforce is supporting both 15-character Case sensitive id and 18-character case insensitive id.

Currently Salesforce provides some built-in options to convert the 15-character id and 18-character id.

  • UI
    • Creating a formula field on the object with function CASESAFEID(Id) to get the 18-char id at the record level.
  • Apex / API
    • When inserting or updating the records, Both 15 character id and 18 character id are accepted. Salesforce internally converts 15 character id to 18 character id to perform the operation.
    • When querying the records, System always export the records in 18 character id. So Apex script using System.debug() or Simple API query using Developer Console or Workbench can show you 18-character id.

Now coming back to actual question how to convert the 15-character id to 18 character id, It is 4 step process.

Let us take a example of this account id : 0010o00002cEs9E

The above image shows the 18-character id for the 15-character id for a sample account record.

Step 1: Split the 15character id into the blocks of 5 characters

0010o00002cEs9E

Step 2: For each block, Read the character one by one from Left to right. If the Character is in between 'A' to 'Z', The value is 1. Otherwise the value is 0.

000000000001001

Output these values in Reverse order.

000000000010010

Step 3: Calculate the binary values for each block

0018

Step 4 : Now get the actual value by comparing with below map. Since each block is a 5 digit binary value, Maximum value in decimal can be 31. The map has characters A-Z and 0-5

ABCDEFGHIJKLMNOPQRSTUVWXYZ012345
012345678910111213141516171819202122232425262728293031
AAS

Just append these characters with 15-character id.

The output for 15character id 0010o00002cEs9E is 0010o00002cEs9EAAS

Sample Code to Convert this in JS (Salesforce Article #: 000319308)

javascript:(function(){
var input=prompt('Enter 15-character ID');
var output;
	if(input.length == 15){
		var addon="";
		for(var block=0;block<3; block++)
		{
			var loop=0;
			for(var position=0;position<5;position++){
				var current=input.charAt(block*5+position);
				if(current>="A" && current<="Z")
					loop+=1<<position;
			}
			addon+="ABCDEFGHIJKLMNOPQRSTUVWXYZ012345".charAt(loop);
		}
		output=(input+addon);
	}
	else{
		alert("Error : "+input+" isn't 15 characters ("+input.length+")");
		return;
	}
prompt('18-character ID:',output);
})();

Thank you for your time in reading this post. Please feel free to comment below if you have any questions or need clarifications on any Salesforce topics.

Cheers

Comments