Home Salesforce Create Customer Community User in Salesforce Apex

Create Customer Community User in Salesforce Apex

by Dhanik Lal Sahni

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 = 'dotnetcodex@gmail.com' + System.now().millisecond() ,
             Alias = 'sfdc',
             Email='dotnetcodex@gmail.com',
             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 = 'dotnetcodex@gmail.com' + System.now().millisecond() ,
    Alias = 'sfdc',
    Email='dotnetcodex@gmail.com',
    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 = 'dhanik.sahni@conduent.com'
    );
    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 = 'dotnetcodex@gmail.com' + System.now().millisecond() ,
                     Alias = 'sfdc',
                     Email='dotnetcodex@gmail.com',
                     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 = 'dhanik.sahni@yahoo.com' + math.random(),
                FirstName = 'Test-First',
                LastName = 'Test-Last',
                Alias = 'test',
                email = 'dhanik.sahni@gmail.com',
                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. 

You may also like

8 comments

Priyanka December 28, 2018 - 12:46 pm

Hi ,
I have requirement like creating community user with person account .i am using your code but getting error.Please help me out.
Account act = new Account(
FirstName = ‘ADemo’,
LastName =’test’,
OwnerId = ‘XXXX’,
AG_Country__c = coun[0].Id,
AG_Email_1__c=’XXXX@gmail.com’,
RecordTypeId =’XXXX’
);
Database.insert(act);
Account is getting inserted.
//User creation
User user1 = new User(
UserName = act.PersonEmail,
FirstName = act.FirstName,
LastName = act.LastName,
Alias = ‘test123’,
email = act.AG_Email_1__c,
ContactId = act.PersonContactId, // getting id here
ProfileId = ‘Community login User Id’,
EmailEncodingKey = ‘UTF-8’,
CommunityNickname = ‘test12345’,
TimeZoneSidKey = ‘America/Los_Angeles’,
LocaleSidKey = ‘en_US’,
LanguageLocaleKey = ‘en_US’
);
Database.insert(user1);
I am getting error…..
System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Cannot create a portal user without contact: [ContactId]

Please tell me.

Reply
Dhanik Lal Sahni December 28, 2018 - 3:10 pm

Please try like this

Account act = new Account(
FirstName = ‘ADemo’,
LastName =’test’,
OwnerId = ‘XXXX’,
AG_Country__c = coun[0].Id,
AG_Email_1__c=’XXXX@gmail.com’,
RecordTypeId =’XXXX’
);
Database.insert(act);

//User creation
User user1 = new User(
UserName = act.PersonEmail,
FirstName = act.FirstName,
LastName = act.LastName,
Alias = ‘test123’,
email = act.AG_Email_1__c,
ProfileId = ‘Community login User Id’,
EmailEncodingKey = ‘UTF-8’,
CommunityNickname = ‘test12345’,
TimeZoneSidKey = ‘America/Los_Angeles’,
LocaleSidKey = ‘en_US’,
LanguageLocaleKey = ‘en_US’
);

String userId;
String password = null;
userId = Site.createExternalUser(user1, act.Id, password, true);

Reply
Mahender December 8, 2019 - 10:40 pm

HI DHANIK LAL,

Is their any way to know community is enabled in org using apex ?

Thanks,
Mahender Reddy.

Reply
Dhanik Lal Sahni December 16, 2019 - 10:08 pm

Hello Mahender, You can use Network object to check this.

Select Id, Name, Status from Network

You can refer document also.

Reply
create customer portal in salesforce - loginfinance.com October 30, 2021 - 3:22 am

[…] Create Customer Community User in Salesforce Apex … […]

Reply
apex create customer community login user Account Official Log In Customer Service Contact Online Info - bankech.com November 23, 2021 - 5:01 am

[…] Create Customer Community User in Salesforce Apex … […]

Reply
Keerti May 15, 2023 - 8:35 pm

There is a problem with person account process , you are not creating contact, so Salesforce is not accepting it, it says you can not create a portal user without contact

Reply
Dhanik Lal Sahni May 17, 2023 - 7:38 pm

Hello Keerti,

Contact is required when you have business account. You have to create portal login for contacts. For person account it is not require.

Thank You,
Dhanik

Reply

Leave a Comment