16

Is there any function in Apex which could emulate functionality of the CASESAFEID() formula function? I'm trying to get 18-char Id variant from the standard one.

2 Answers 2

37

Per the Apex docs on primitive datatypes, "Note that if you set [an] ID to a 15-character value, Apex automatically converts the value to its 18-character representation." So it should be enough to assign your 15 character id to an ID-typed variable, and then back to a string, like so:

string idStr = '001E000000nwg7g';   // 15 character id
id idval = idStr;                   // assign to ID variable
idStr = idval;                      // back to string to prove the point
system.debug('18 char: ' + idStr);  // note that you could just append idval instead
                                    // of converting to string first

Remember that assigning an invalid id string to an ID-typed variable will throw an exception; if there's any chance that your 15 character value may not be a valid id, wrap the assignment in a try/catch block.

3
  • Good enough for me :) Thank you, Jason!
    – dino ursic
    Commented Jan 30, 2014 at 14:06
  • Thanks for breaking this down line by line for understanding. Assuming you start with accountId as a 15 char string, one could get this done in one line: accountId = (String)(Id)accountId. Commented Dec 30, 2019 at 17:28
  • @SwisherSweet in fact, you can just use accountId = (Id)accountId;, as Id values are always implicitly cast to 18-character strings whenever they are used as strings. Commented Dec 30, 2019 at 18:33
2

You can just type the string cast to ID. Like (Id) idStr;

You must log in to answer this question.

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