If there is a exception when using site.createPortalUser, a null is returned and the site system administrator is sent an email. For more information on sites, see “Salesforce Sites” in the Salesforce online help.
In the example below, you must enter the account ID of the account that you want to associate with new portal users. You must also add the account owner to the role hierarchy for this code example to work. For more information, see “Setting Up Your Customer Portal” in the Salesforce online help.
/** * An Apex class that creates a portal user */ public class SiteRegisterController { // PORTAL_ACCOUNT_ID is the account on which the contact will be created on // and then enabled as a portal user. //Enter the account ID in place of <portal_account_id> below. private static Id PORTAL_ACCOUNT_ID = '<portal_account_id>'; public SiteRegisterController () { } public String username {get; set;} public String email {get; set;} public String password {get; set {password = value == null ? value : value.trim(); } } public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } } public String communityNickname {get; set { communityNickname = \ value == null ? value : value.trim(); } } private boolean isValidPassword() { return password == confirmPassword; } public PageReference registerUser() { // If password is null, a random password is sent to the user if (!isValidPassword()) { ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match); ApexPages.addMessage(msg); return null; } User u = new User(); u.Username = username; u.Email = email; u.CommunityNickname = communityNickname; String accountId = PORTAL_ACCOUNT_ID; // lastName is a required field on user, but if it isn't specified, the code uses the username String userId = Site.createPortalUser(u, accountId, password); if (userId != null) { if (password != null && password.length() > 1) { return Site.login(username, password, null); } else { PageReference page = System.Page.SiteRegisterConfirm; page.setRedirect(true); return page; } } return null; } }
/** * Test class. */ @isTest private class SiteRegisterControllerTest { // Test method for verifying the positive test case static testMethod void testRegistration() { SiteRegisterController controller = new SiteRegisterController(); controller.username = 'test@force.com'; controller.email = 'test@force.com'; controller.communityNickname = 'test'; // registerUser always returns null when the page isn't accessed as a guest user System.assert(controller.registerUser() == null); controller.password = 'abcd1234'; controller.confirmPassword = 'abcd123'; System.assert(controller.registerUser() == null); } }
<apex:page id="Registration" showHeader="false" controller= "SiteRegisterController" standardStylesheets="true"> <apex:outputText value="Registration"/> <br/> <apex:form id="theForm"> <apex:messages id="msg" styleClass="errorMsg" layout="table" style="margin-top:1em;"/> <apex:panelGrid columns="2" style="margin-top:1em;"> <apex:outputLabel value="{!$Label.site.username}" for="username"/> <apex:inputText required="true" id="username" value="{!username}"/> <apex:outputLabel value="{!$Label.site.community_nickname}" for="communityNickname"/> <apex:inputText required="true" id="communityNickname" required="true" value="{!communityNickname}"/> <apex:outputLabel value="{!$Label.site.email}" for="email"/> <apex:inputText required="true" id="email" required="true" value="{!email}"/> <apex:outputLabel value="{!$Label.site.password}" for="password"/> <apex:inputSecret id="password" value="{!password}"/> <apex:outputLabel value="{!$Label.site.confirm_password}" for="confirmPassword"/> <apex:inputSecret id="confirmPassword" value="{!confirmPassword}"/> <apex:outputText value=""/> <apex:commandButton action="{!registerUser}" value="{!$Label.site.submit}" id="submit"/> </apex:panelGrid> </apex:form> </apex:page>
String accountId = PORTAL_ACCOUNT_ID; String userId = Site.createPortalUser(u, accountId, password);
String ownerId = OWNER_ID; String userId = Site.createPersonAccountPortalUser(u, ownerId, password);
The following are methods for Site. All methods are static.
public static System.PageReference changePassword(String newPassword, String verifyNewPassword, String oldPassword)
Type: System.PageReference
public static Id createExternalUser(SObject user, String accountId)
The email address of the user is used to look for matching contacts associated with the specified accountId. If a matching contact is found and is already used by an external user, a new contact is created. If a matching contact is found but isn’t used by an external user, it is used for the new external user. If there is no matching contact, a new contact is created for the new external user.
This method throws Site.ExternalUserCreateException when user creation fails.
The nickname field is required for the User sObject when using the createExternalUser method.
This method is only valid when a site is associated with a Customer Portal.
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
public static Id createExternalUser(SObject user, String accountId, String password)
The email address of the user is used to look for matching contacts associated with the specified accountId. If a matching contact is found and is already used by an external user, a new contact is created. If a matching contact is found but isn’t used by an external user, it is used for the new external user. If there is no matching contact, a new contact is created for the new external user.
This method throws Site.ExternalUserCreateException when user creation fails.
The nickname field is required for the User sObject when using the createExternalUser method.
This method is only valid when a site is associated with a Customer Portal.
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
public static Id createExternalUser(SObject user, String accountId, String password, Boolean sendEmailConfirmation)
The email address of the user is used to look for matching contacts associated with the specified accountId. If a matching contact is found and is already used by an external user, a new contact is created. If a matching contact is found but isn’t used by an external user, it is used for the new external user. If there is no matching contact, a new contact is created for the new external user.
This method throws Site.ExternalUserCreateException when user creation fails.
The nickname field is required for the User sObject when using the createExternalUser method.
This method is only valid when a site is associated with a Customer Portal.
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
public static ID createPersonAccountPortalUser(sObject user, String ownerId, String password)
Type: ID
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
This method is only valid when a site is associated with a Customer Portal, and when the user license for the default new user profile is a high-volume portal user.
public static ID createPersonAccountPortalUser(sObject user, String ownerId, String recordTypeId, String password)
Type: ID
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
This method is only valid when a site is associated with a Customer Portal, and when the user license for the default new user profile is a high-volume portal user.
public static ID createPortalUser(sObject user, String accountId, String password, Boolean sendEmailConfirmation)
Type: ID
If you’re using API version 34.0 or later, we recommend using the createExternalUser() methods because they offer better error handling than this method.
The nickname field is required for the user sObject when using the createPortalUser method.
This method is only valid when a site is associated with a Customer Portal.
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
public static Boolean forgotPassword(String username)
Type: Boolean
The return value will always be true unless it’s called outside of a Visualforce page, it will be false.
Calls to this method in API version 30.0 and later won’t commit the transaction automatically. Calls to this method prior to API version 30.0 commit the transaction, making it impossible to roll back to a save point before the call.
public static String getAnalyticsTrackingCode()
Type: String
Note that this may return the referring page's URL instead of the current request's URL. The returned value includes the path prefix and always ends with a / character. If the current request is not a site request, then this method returns null. If the current request is not a site request, then this method returns null. This method was replaced by getBaseUrl in API version 30.0.
public static String getCurrentSiteUrl()
Type: String
Use getBaseUrl() instead.
public static String getBaseCustomUrl()
Type: String
This method replaces getCustomWebAddress() and includes the custom URL's path prefix.
public static String getBaseInsecureUrl()
Type: String
public static String getBaseRequestUrl()
Type: String
public static String getBaseSecureUrl()
Type: String
public static String getBaseUrl()
Type: String
This method replaces getCurrentSiteUrl().
Returns the request's custom URL if it doesn't end in Lightning Platform or returns the site's primary custom URL. If neither exist, then this returns null. Note that the URL's path is always the root, even if the request's custom URL has a path prefix. If the current request is not a site request, then this method returns null. The returned value always ends with a / character.
public static String getCustomWebAddress()
Type: String
Use getBaseCustomUrl() instead.
public static String getDomain()
Type: String
public static String getErrorDescription()
Type: String
public static String getErrorMessage()
Type: String
public static String getExperienceId()
Type: String
Use the getExperienceId and setExperienceId methods to implement dynamic login experiences. You can set the experience ID with setExperienceId or by extending the following endpoints with expid_value.
The cookie is set when the browser loads the URLs with the expid values.
public static String getMasterLabel()
Type: String
public static String getName()
Type: String
public static String getOriginalUrl()
Type: String
public static String getPasswordPolicyStatement()
Type: String
public static String getPathPrefix()
Type: String
Returns the URL path prefix of the current site. For example, if your site URL is myco.force.com/partners, /partners is the path prefix. Returns null if the prefix isn’t defined. If the current request is not a site request, then this method returns a null.
public static String getPrefix()
Type: String
public static String getSiteId()
Type: Id
public static System.PageReference getTemplate()
Type: System.PageReference
public static String getSiteType()
Type: String
public static String getSiteTypeLabel()
Type: String
public static Boolean isLoginEnabled()
Type: Boolean
public static Boolean isPasswordExpired()
Type: Boolean
public static Boolean isRegistrationEnabled()
Type: Boolean
public static System.PageReference login(String username, String password, String startUrl)
Type: System.PageReference
All DML statements before the call to Site.login get committed. It’s not possible to roll back to a save point that was created before a call to Site.login.
Do not include http:// or https:// in the startURL.
public static System.PageReference passwordlessLogin(Id userId, List<Auth.VerificationMethod> methods, String startUrl)
Type: System.PageReference
Include this method in the Apex controller of a custom login page implementation.
Here’s a simple code example of an Apex controller containing the passwordlessLogin method. The PageReference returned by passwordlessLogin redirects the user to the Salesforce verification page. If the user enters the correct code, the user is redirected to the community page specified by the start URL.
global with sharing class MFILoginController { //Input variables global String input {get; set;} public String startURL {get; set;} public List<Auth.VerificationMethod> methods; public String error; global MFILoginController() { // Add verification methods in priority order methods = new List<Auth.VerificationMethod>(); methods.add(Auth.VerificationMethod.SMS); methods.add(Auth.VerificationMethod.EMAIL); methods.add(Auth.VerificationMethod.U2F); methods.add(Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR); methods.add(Auth.VerificationMethod.TOTP); } global PageReference login() { List<User> users = null; // Empty input if(input == null || input == '') { error = 'Enter Username'; return null; } users = [select name, id, email from User where username=:input]; if(users == null || users.isEmpty()) { error = 'Can\'t find a user'; return null; } if (startURL == null) startURL = '/'; return Site.passwordlessLogin(users[0].id, methods, startURL); } }
public static void setExperienceId(String expIdValue)
The value must contain alphanumeric characters only, up to 30 characters.
Use setExperienceId when you’re implementing dynamic login experiences. A login experience refers to a login page plus any secondary pages associated with the login page (such as 2FA authentication or a login flow). You define different login experiences depending on who users are or where they’re logging in from. For example, you can require a different registration process based on the user’s location. In this case, expIdValue includes a state or country code. When the user logs in, the URL contains the experience ID parameter, {expid}. The {expid} parameter is replaced by the value stored in expIdValue, such as .jp. Then the user is redirected to the Japanese login experience.
String expid = ApexPages.currentPage().getParameters().get('expid'); if (expId != null) { Site.setExperienceId(expId); }
public static Void setPortalUserAsAuthProvider(sObject user, String contactId)
Type: Void
public static void validatePassword(SObject user, String password, String confirmPassword)
Type: void