+ Start a Discussion
rtscottrtscott 

Defining a random string for a variable?

Hello All,

 

I have - what is likely to be - a simple question:

 

I am setting up an Apex trigger to create Customer Portal Users from Contacts. When I create the Customer Portal User, I need to assign an 'Alias' for the new User account. I need to come up with a way to create aliases that are unique, so that my trigger doesn't fail when it tries to create a Portal User using an alias that already exists. I'm thinking I need to somehow use a random number in the Alias. So far I have this:

 

String alias = ''; if (c.FirstName != null) alias = 'GP-' + c.FirstName.substring(0,3) + c.LastName.substring(0,2); else alias = 'GP-' + c.LastName.substring(0,2);

 

Keep in mind that the 'Alias' field on the User can only be a 8 characters max. What would be best best way to make unique aliases using a random string? (In my example, there is a 'CP-' prefix for "Customer Portal" - I don't necessarily need that.)

 

Here is the full create portal user code, if interested (please feel free to point out any glaring errors - I am new to this!):

 

if (createflag) { String alias = ''; if (c.FirstName != null) alias = 'GP-' + c.FirstName.substring(0,3) + c.LastName.substring(0,2); else alias = 'GP-' + c.LastName.substring(0,2); Database.DMLOptions dmo = new Database.DMLOptions(); dmo.EmailHeader.triggerUserEmail = true; User u = new User(Alias=alias, Email=c.email, FirstName=c.FirstName, LastName=c.LastName, Username=c.Email, ProfileId='00e60000000abCD', LocaleSidKey='en_US', TimezoneSidKey='America/Los_Angeles', ContactId=c.Id, EmailEncodingKey='UTF-8', LanguageLocaleKey='en_US'); ulist.add(u); u.setOptions(dmo); contactIds.add(c.Id); }

 

Message Edited by rtscott on 04-30-2009 12:34 PM
rtscottrtscott

I actually figured our a pretty good way to do this using the Contact's Last Name and their Id:

 

String alias = 'P' + c.LastName.substring(0,2) + (''+c.Id).substring(10,15);

 

This creates a unique (enough) alias and seems like it will work. In anyone has a better idea, I am all ears.

 

-- Rob

Message Edited by rtscott on 04-30-2009 01:39 PM