+ Start a Discussion
Bhu'1 salesforceBhu'1 salesforce 

Trigger to create a community user from contact ? facing some issue ? Please help...

Hi All,

I have created a trigger to create a community user direct from contact. Facing some issue ? Please review the code and let me know..
Code :
trigger UserFromContact on Contact (after insert) {
set<ID> conids = new set<ID>();
    for(Contact c : trigger.new){
        if(c.accountid != Null && c.recordtype ='Customer_Contact'){
            conids.add(c.id);           
    }  
}
List<contact> conlist = [select id,email,firstName,lastname,accountId from Contact where Id IN : conids];
List<user> usr = new List<user>();
    for(Contact con : conlist){
     string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):''; nick += Datetime.now().getTime();       
    User newUser = 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 = 'America/Los_Angeles',
                    username = con.email,
                    CommunityNickname = nick,
                    ProfileId = '00e1a000000V5BU',
                    IsActive = true);
                    usr.add(newUser);        
    }    
     Insert usr;
}

error : while creating an contact :
System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: con.firstName (max length=8): [Alias]:
Best Answer chosen by Bhu'1 salesforce
Bhu'1 salesforceBhu'1 salesforce
Fixed the above error related to alias, (alias = string.valueof(con.FirstName.substring(0,1) + con.LastName.substring(0,1)), )
error :
UNKNOWN_EXCEPTION, portal account owner must have a role: