-1

I am allocating a customer community user license whenever a lead is converted into contact and it's working fine. below is my code:

trigger CreateCommunityUser on Contact (After insert) {
        
    if(Trigger.isInsert){
        for(Contact co : trigger.new){
            Contact con = [select id,email,firstName,lastname,accountId from Contact where Id =:co.Id];         
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.EmailHeader.triggerUserEmail = false;       
            dmo.EmailHeader.triggerOtherEmail = false;
            dmo.EmailHeader.triggerAutoResponseEmail = false;       
            dmo.optAllOrNone = false; */
    
            // create portal user
            string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):'';
            nick += Datetime.now().getTime();
            User newUser1 = new User(alias=con.firstName, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_US',contactId = con.Id,timezonesidkey = 'Asia/Dubai',username = con.email,CommunityNickname = nick,ProfileId ='00e6F000001kZ4C', IsActive = true);
            newUser1.setOptions(dmo); 
            insert newUser1;
        }
    }
}

Because of this code, most of my other test classes are failing with these errors:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateCommunityUser: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: FirstName (max length=8): [Alias] Trigger.CreateCommunityUser: line 16, column 1: [] FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateCommunityUser: execution of AfterInsert

Please guide me where am I going wrong. Thanks already.

1
  • 2
    The error spells it out STRING_TOO_LONG, Alias: data value too large: FirstName (max length=8). There are other issues (query in a loop, you shouldn't need the query at all, not checking if the contact has been converted from a lead, DML inside a loop), but the alias length is the primary issue.
    – Derek F
    Jan 19 at 16:03
3

The maximum length of User.Alias (8) is significantly shorter than the maximum length of ContactFirstName (40). You need to truncate to fit. Often the String.abbreviate method is most convenient for this purpose, but for Alias you should probably prefer substring.

Your code should look something like:

String alias = con.firstName;
if (alias.length() > 8)
    alias = alias.substring(0, 8);
insert new User(Alias = alias, ...);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.