[SalesForce] Create User from Contact

I need to create a trigger that will create a user(from contact) when the checkbox = true. This code saves, is active but doesnt create user.

trigger createUserfromContact on Contact (after update) {
List <Contact> newCon = new List<Contact>(); 
List <Contact> newRegCon = new List<Contact>(); 
List <User> newUser1 = new List<User>();

    for(Contact con : Trigger.new){
        newCon.add(con);     
    }
    for(Contact con : [Select Id,ESS_User__c from Contact WHERE Id =: newcon ]){

       if (con.ESS_User__c == TRUE){
           for(User userqry1 : [Select Id, ContactId from User WHERE ContactId =:newCon ]){
            newUser1.add(userqry1);

                if(newUser1.isEmpty()){
                    User newUser = new User( 
                    CommunityNickname = con.FirstName + con.LastName.substring(0,3),
                    ContactId = con.id,
                    Department = con.Department,
                    Email = con.Email,
                    EmailEncodingKey = 'ISO-8859-1',
                    EmployeeNumber= con.Employee_No__c,
                    FirstName = con.FirstName,
                    IsActive = TRUE,     
                    LastName = con.LastName,
                    PortalRole = '00e28000000NWUUAA4', 
                    ReceivesInfoEmails= TRUE,
                    Username = con.Email,
                    UserPermissionsChatterAnswersUser= TRUE,
                    UserRoleId = '  00E28000000JZDUEA4'
                    );
                    insert newUser;   

                }
            }
        }
    }   
}

Best Answer

Try this ;)

trigger createUserfromContact on Contact (after update) {     
    List <User> newUsers = new List<User>();
    List <User> existingUsers = new List<User>();

    for(Contact con : Trigger.NEW){
       if (con.ESS_User__c == TRUE){
            existingUsers = [Select Id, ContactId from User WHERE ContactId = :con.ID];
            if(existingUsers.isEmpty()){
                newUsers.add(new User( 
                CommunityNickname = con.FirstName + con.LastName.substring(0,3),
                ContactId = con.id,
                Department = con.Department,
                Email = con.Email,
                EmailEncodingKey = 'ISO-8859-1',
                EmployeeNumber= con.Employee_No__c,
                FirstName = con.FirstName,
                IsActive = TRUE,     
                LastName = con.LastName,
                PortalRole = '00e28000000NWUUAA4', 
                ReceivesInfoEmails= TRUE,
                Username = con.Email,
                UserPermissionsChatterAnswersUser= TRUE,
                UserRoleId = '00E28000000JZDUEA4'));
            }
        }
    }   
    insert newUsers;
}
Related Topic