Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, August 16
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Integration List
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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

    Prevent Large Data Queries in Salesforce with Transaction Security Policies

    August 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 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
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) 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

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • 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
    Archives
    Categories
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) 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.