2

I am trying to generate another ID in Salesforce using a after insert, after update trigger. I wish to use this unique identifier as a URL parameter so it has to contain characters that are url parameter friendly.

I have written a simple trigger that generates a unique string based on the id of the record:

trigger InvitationKeyAfterInsertUpdate on CampaignMember (after insert, after update) {
for (CampaignMember i : Trigger.new) {
    //Only generate key when value not present
    if (i.Key__c == null) {
        //Random private key to ensure Key__c is secure (can't be guessed/generated)
        Blob privateKey = EncodingUtil.base64Decode('046QdQEH24AgGafkkot8gg==');

        //We use encryption on the Id instead of hashing because encryption will not produce collisions. This will never need to be decrypted.
        update new CampaignMember (Id = i.Id, Key__c = EncodingUtil.base64Encode(Crypto.encryptWithManagedIV('AES128', privateKey, Blob.valueOf(i.Id))));
    }
}

My issue is that when the string is generated, it contains characters such as "/" and "+" that break the url parameter, so in theory I would like the string to only contain A-Za-z0-9.

I can of course strip the characters once the string is generated, but my issue is that if I have the two string 'ab+c' and 'a+bc', when the character '+' is stripped they will both be 'abc' which defeats the whole purpose of ensuring the fields will be unique.

Can anyone help out?

2
  • if you just need some valid, one-time, SFDC id, why not just create some arbitrary SFDC object via an insert, grab the id, and then delete the object?
    – cropredy
    Dec 22, 2014 at 23:20
  • @crop1645 a valid suggestion but for the sake of growth I wish to limit unnecessary DML especially in a Trigger. I am sure there must be a way of limiting the characters generated either in this method or using a different method. Dec 22, 2014 at 23:33

1 Answer 1

2

As long as your only concern is generating a unique ID that can safely be included in a URL querystring, you could just escape ("urlEncode") the output of your current code:

EncodingUtil.urlEncode(EncodingUtil.base64Encode(Crypto.encryptWithManagedIV('AES128', privateKey, Blob.valueOf(i.Id))),'UTF-8')
2
  • 1
    With the slight change: EncodingUtil.urlEncode(EncodingUtil.base64Encode(Crypto.encryptWithManagedIV('AES128', privateKey, Blob.valueOf(i.Id))),'UTF-8') That works perfect. Thank you! Dec 23, 2014 at 3:38
  • Ah! Excellent. Thanks, David. I'll update my answer to include the missing parameter. Dec 23, 2014 at 4:09

You must log in to answer this question.

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