Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    • Salesforce Spring ’25 Release: Top Flow Enhancements You Need to Know
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 8
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Create Customer Community User in Salesforce Apex

    Create Customer Community User in Salesforce Apex

    Dhanik Lal SahniBy Dhanik Lal SahniMay 25, 2018Updated:May 25, 20188 Comments4 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Create Customer Community User in Salesforce Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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. 

    community user lightning portal user salesforce
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleSalesforce Summer ’18 Release Notes
    Next Article Create Signature Pad in Salesforce Lightning
    Dhanik Lal Sahni
    • Website

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Basic Queueable Chaining in Salesforce Apex

    March 31, 2025
    View 8 Comments

    8 Comments

    1. Priyanka on 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 on 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
    2. Mahender on 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 on 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
    3. Pingback: create customer portal in salesforce - loginfinance.com

    4. Pingback: apex create customer community login user Account Official Log In Customer Service Contact Online Info - bankech.com

    5. Keerti on 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 on 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 Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.