Tag:

portal user

    Create Customer Community User in Salesforce Apex

    Community Portal is great product from Salesforce.  This offers many features to address business customer’s issues. Portal can be created in Visual Force and Lightning.  Lightning support great features like SPA Application using Aura Framework or Angular.

    For each community we need users to work on. We can create community users using CRM admin but when we support self registration with custom logic then we have to use Apex classes.  Let us see how to create Portal User using Apex.

    We can use below concept for creating portal user

    1. Use Site classes
    2. Create user using User class with ContactId

    Portal user can be created for Business and Personal Account. For Business user we need Contact record for Account also.

    Portal User Creation For Personal Account:

    Steps for Portal User Creation for Personal Account:

    1. Create User Role
    2. Create Personal Account with above role
    3. Create Portal User with PersonContactId

    Portal User Creation For Business Account:

    1. Create User Role
    2. Create Business Account with above role
    3. Create Contact for Business Account
    4. Create Portal User with ContactId

    Let us create Portal User for Personal Account:

    1. Create User Role
      //Create portal account owner
      UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
      Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
      User portalAccountOwner1 = new User(
               UserRoleId = portalRole.Id,
               ProfileId = profile1.Id,
               Username = '[email protected]' + System.now().millisecond() ,
               Alias = 'sfdc',
               Email='[email protected]',
               EmailEncodingKey='UTF-8',
               Firstname='Dhanik',
               Lastname='Sahni',
               LanguageLocaleKey='en_US',
               LocaleSidKey='en_US',
               TimeZoneSidKey='America/Chicago'
      );
      Database.insert(portalAccountOwner1);
      
    2. Create Personal Account with above role
       Account act = new Account(
               FirstName = 'Dhanik',
               LastName ='Sahni',
               OwnerId = portalAccountOwner1.id
      );
      Database.insert(act);
      
    3. Create Portal User with PersonContactId
      //Create user
      Profile portalProfile = [SELECT Id FROM Profile WHERE Name='Community Portal' Limit 1];
              User user1 = new User(
                  UserName = act.PersonEmail,
                  FirstName = act.FirstName,
                  LastName = act.LastName,
                  Alias = 'test123',
                  email = act.PersonEmail,
                   ContactId = act.PersonContactId,
                   ProfileId = portalProfile.Id,
                   EmailEncodingKey = 'UTF-8',
                   CommunityNickname = 'test12345',
                   TimeZoneSidKey = 'America/Los_Angeles',
                   LocaleSidKey = 'en_US',
                   LanguageLocaleKey = 'en_US'
      );
      Database.insert(user1);
      

    Steps to create Portal user for Business Accounts

    1. Create User Role
      //Create portal account owner
      UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
      Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
      User portalAccountOwner1 = new User(
               UserRoleId = portalRole.Id,
               ProfileId = profile1.Id,
               Username = '[email protected]' + System.now().millisecond() ,
               Alias = 'sfdc',
               Email='[email protected]',
               EmailEncodingKey='UTF-8',
               Firstname='Dhanik',
               Lastname='Sahni',
               LanguageLocaleKey='en_US',
               LocaleSidKey='en_US',
               TimeZoneSidKey='America/Chicago'
      );
      Database.insert(portalAccountOwner1);
      
    2. Create Business Account with above role
      //Create account
              
      Account act = new Account(
               Name = 'Dhanik Sahni',
               OwnerId = portalAccountOwner1.id
      );
      Database.insert(act);
    3. Create Contact for Business Account
      //Create contact
      Contact contact1 = new Contact(
                   FirstName = 'Test',
                   Lastname = 'McTesty',
                   AccountId = act.Id,
                   Email = '[email protected]'
      );
      Database.insert(contact1);
    4. Create Portal User with ContactId
        //Create Portal User
      Profile portalProfile = [SELECT Id FROM Profile WHERE Name='Community Portal' Limit 1];
      User user1 = new User(
                  UserName = act.PersonEmail,
                  FirstName = act.FirstName,
                  LastName = act.LastName,
                  Alias = 'test123',
                  email = act.PersonEmail,
                   ContactId = contact1.Id,
                   ProfileId = portalProfile.Id,
                   EmailEncodingKey = 'UTF-8',
                   CommunityNickname = 'test12345',
                   TimeZoneSidKey = 'America/Los_Angeles',
                   LocaleSidKey = 'en_US',
                   LanguageLocaleKey = 'en_US'
      );
      Database.insert(user1);
      

    Create Portal User using Site Class

        public static string CreateSiteUser()
        {
            //Create portal account owner
                UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
                Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
                User portalAccountOwner1 = new User(
                         UserRoleId = portalRole.Id,
                         ProfileId = profile1.Id,
                         Username = '[email protected]' + System.now().millisecond() ,
                         Alias = 'sfdc',
                         Email='[email protected]',
                         EmailEncodingKey='UTF-8',
                         Firstname='Dhanik',
                         Lastname='Sahni',
                         LanguageLocaleKey='en_US',
                         LocaleSidKey='en_US',
                         TimeZoneSidKey='America/Chicago'
                );
                Database.insert(portalAccountOwner1);
    
                 Account act = new Account(
                         FirstName = 'Dhanik',
                         LastName ='Sahni',
                         OwnerId = portalAccountOwner1.id
                );
                Database.insert(act);
                
            	Profile p=[Select Id from Profile where Name='Community Portal' LIMIT 1];
            	User u = New User(
                    UserName = '[email protected]' + math.random(),
                    FirstName = 'Test-First',
                    LastName = 'Test-Last',
                    Alias = 'test',
                    email = '[email protected]',
                    CommunityNickName = string.valueOf(math.random()).substring(0,6),
                    ProfileID = p.id,
                    TimeZoneSidKey = 'America/New_York', 
                    LocaleSidKey = 'en_US', 
                    EmailEncodingKey = 'UTF-8', 
                    LanguageLocaleKey = 'en_US'
                );
            	string userId='';
           		try {
                	userId = Site.createExternalUser(u, act.Id, null);
                    System.Debug(userId);
                } catch(Site.ExternalUserCreateException ex) {
                    List errors = ex.getDisplayMessages();
                    for (String error : errors)  {
                          System.debug(LoggingLevel.Error,'Errrors:' + error);
                 }
            }
                
            return userId;
        }
    

    Errors which may thrown while user creation:

    System.TypeException: You are already logged in.  : As per error, you are already logged in Salesforce. So please logged out and then try againa.

    “portal user already exists for contact” :  user is already exist with username, Even though user is deactivated, it will not create new user with username. Change the username and try again.

    portal account owner must have a role :  Account for which user is being created, It’s owner does not have  any role assigned. Assign some role to account owner.

    Alias: data value too large: Portal null (max length=8) : User.Alias should have maximum of 8 character.  Check value of this field. 

    May 25, 2018 2 comments
    0 Facebook Twitter Google + Pinterest