I have to generate a Unique number for every record in a object.I can't use the Auto-number and SFDC ID of the record.
It's a kind of External ID that external System can use to identify the records.
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityI have to generate a Unique number for every record in a object.I can't use the Auto-number and SFDC ID of the record.
It's a kind of External ID that external System can use to identify the records.
If you really, really need to do this, you could try this:
String s = record.createDateTime.format(); // or some other datetime
Blob hash = Crypto.generateDigest('MD5', Blob.valueOf(s));
String uniqueString = EncodingUtil.convertToHex(hash);
return uniqueString;
You'd need to use it in an oncreate
trigger and update the record with this value.
If the string was too long, you could just chop it off at some point using theString.substring(start,numChars);
Elaborating on Caspar Harmer's answer:
Blob hash = Crypto.generateDigest('MD5', Blob.valueOf(s));
is very expensive CPU Time wise.
The following test timed out for me, as did a loop of 1000:
@isTest
private static void testIdUniquenessMultipleCalls () {
Set<String> ids = new Set<string>();
for(Integer i = 0; i < 10000; i++) {
ids.add(Utility.getUniqueId());
}
system.assertEquals(10000,ids.size(),'consecutive calls must produce distinct Ids');
}
I always received a CPU Time Limit exception.
Here's a version that passes the test:
public static String getUniqueId(){
String milliseconds = String.ValueOf(System.Now().getTime()); //unix timestamp
Blob pseudoHash = Blob.ValueOf(milliseconds + String.ValueOf(Crypto.getRandomInteger()));
String uniqueString = EncodingUtil.convertToHex(pseudoHash);
uniqueString = uniqueString.length() > 255 ? uniqueString.substring(0,255) : uniqueString;
return uniqueString;
}