Creating portal user through trigger

Portal user will be created if unique email is inserted in contact.If user is already created, no new portal user will be created for that contact.


trigger CreatePortalUser on Contact (after insert, after update) {
List usersToInsert = new List();
List ExistingUsers = [Select contactId from User where contactId in: Trigger.NewMap.keySet()];
Set contactsHavingUsers = new Set();
for(User u : ExistingUsers) {
contactsHavingUsers.add(u.Id);
}
Profile portalProfile = [select id, name from profile where name='Portal User']; //Portal User is a custom profile already set up for your customer portal
String aliasVar = '';
for(Contact con : Trigger.New) {
if(!contactsHavingUsers.contains(con.Id) && con.Email != null) {
if((con.LastName).length() > 8) {
aliasVar = (con.LastName).substring(0, 8);
} else {
aliasVar = con.LastName;
}
User testUser = new User(alias = aliasVar, email = con.Email,
emailencodingkey='UTF-8', lastname=con.LastName, languagelocalekey='en_US',
localesidkey='en_US', profileid = portalProfile.Id,
timezonesidkey='America/Los_Angeles', username = con.Email, contactId=con.Id);
usersToInsert.add(testUser);
}
}
// Set the DML options
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = true;
Database.insert(usersToInsert, dlo);
}

Email and temporary password will be sent to user’s email id.

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply