Ensuring the nickname created is unique
Note: This update can only occur within Sandbox and then perform a change set to Production in order to save those changes. For additional information, please see: Deploy change sets from sandbox to production.
Step 1: Add TX_UniqueNicknameHelper Apex Class
- Navigate to Setup and search for Apex Classes.
- Select the New button.
- Paste the following into the new class or copy it from here:
public class TX_UniqueNicknameHelper { public static List<User> getMatchingUsers(List<User> triggerNew) { Set<String> nicknames = new Set<String>(); for(User u : triggerNew) { nicknames.add(u.CommunityNickname); } return [ select Id, CommunityNickname from User where CommunityNickname IN :nicknames ]; } // there is unique check on username as well, so we reliably fallback on this public static String getUniqueNickname(User u) { String username = u.Username; String[] parts = username.split('@'); if(parts.size() == 2) { return parts[0] + '_' + parts[1]; } else { return parts[0] + '_' + Datetime.now().getTime(); } } }
- Save your changes.
Step 2: Add TX_UniqueNicknameTests Apex Class
- Navigate to Setup and search for Apex Classes.
- Select the New button.
- Copy the code from this file
Note: The copied code references ‘Customer Community Plus User’ - if your institution uses a different Community Profile, you should update these references to the appropriate Profile name.
- Save your changes.
Step 3: Add TX_MakeUniqueNickname Apex Trigger
- Navigate to Setup and search for User.
- Select Triggers.
- Select the New button.
- Highlight the contents in the window and paste the following into the new trigger or copy it from here:
trigger TX_MakeUniqueNickname on User (before insert) { if(Trigger.isBefore) { if(Trigger.isInsert) { // find matching users List<User> matchingUsers = TX_UniqueNicknameHelper.getMatchingUsers(Trigger.new); if(matchingUsers.size() != 0) { for(User u : Trigger.new) { for(User matchingUser : matchingUsers) { if(String.isNotBlank(u.CommunityNickname) && u.CommunityNickname.equals(matchingUser.CommunityNickname)) { u.CommunityNickname = TX_UniqueNicknameHelper.getUniqueNickname(u); } } } } } } }
- Save your changes.