Skip to main content

Return to TX Community

Liaison

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

  1. Navigate to Setup and search for Apex Classes.
  2. Select the New button.
  3. 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();
        }
  }
}
  1. Save your changes.

 Step 2: Add TX_UniqueNicknameTests Apex Class

  1. Navigate to Setup and search for Apex Classes.
  2. Select the New button.
  3. 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.  

  1. Save your changes.

Step 3: Add TX_MakeUniqueNickname Apex Trigger

  1. Navigate to Setup and search for User.
  2. Select Triggers.
  3. Select the New button.
  4. 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);
                        }
                    }
                }
            }
        }
    }
}
  1. Save your changes.

 

  • Was this article helpful?