Site Class

Use the Site Class to manage your Force.com sites.

Namespace

System

Usage

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 “Force.com Sites Overview” in the Salesforce online help.

Force.com Sites Examples

The following example creates a class, SiteRegisterController, which is used with a Visualforce page (see markup below) to register new Customer Portal users.
Note
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); } }
The following is the Visualforce registration page that uses the SiteRegisterControllerApex controller above:
<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> cod</apex:page>
The sample code for the createPersonAccountPortalUser method is nearly identical to the sample code above, with the following changes:
  • Replace all instances of PORTAL_ACCOUNT_ID with OWNER_ID.
  • Determine the ownerID instead of the accountID, and use the createPersonAccountPortalUser method instead of the CreatePortalUser method by replacing the following code block:
    String accountId = PORTAL_ACCOUNT_ID;
    String userId = Site.createPortalUser(u, accountId, password);
    
    with
    String ownerId = OWNER_ID;
    String userId = Site.createPersonAccountPortalUser(u, ownerId, password);
    

Site Methods

The following are methods for Site. All methods are static.

changePassword(String, String, String)

Changes the password of the current user.

Signature

public static System.PageReference changePassword(String newpassword, String verifynewpassword, String opt_oldpassword)

Parameters

newpassword
Type: String
verifynewpassword
Type: String
opt_oldpassword
Type: String

Return Value

Type: System.PageReference

Usage

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.

createPersonAccountPortalUser(sObject, String, String)

Creates a person account using the default record type defined on the guest user's profile, then enables it for the site's portal.

Signature

public static ID createPersonAccountPortalUser(sObject user, String ownerId, String password)

Parameters

user
Type: sObject
ownerId
Type: String
password
Type: String

Return Value

Type: ID

Usage

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.

Note
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.

createPersonAccountPortalUser(sObject, String, String, String)

Creates a person account using the specified recordTypeID, then enables it for the site's portal.

Signature

public static ID createPersonAccountPortalUser(sObject user, String ownerId, String recordTypeId, String password)

Parameters

user
Type: sObject
ownerId
Type: String
recordTypeId
Type: String
password
Type: String

Return Value

Type: ID

Usage

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.

Note
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.

createPortalUser(sObject, String, String, Boolean)

Creates a portal user for the given account and associates it with the site's portal.

Signature

public static ID createPortalUser(sObject user, String accountId, String opt_password, Boolean opt_sendEmailConfirmation)

Parameters

user
Type: sObject
accountId
Type: String
opt_password
Type: String
(Optional) The password of the portal user. If not specified, or if set to null or an empty string, this method sends a new password email to the portal user.
opt_sendEmailConfirmation
Type: Boolean
(Optional) Determines whether a new user email is sent to the portal user. Set it to true to send a new user email to the portal user. The default is false, that is, the new user email isn't sent.

Return Value

Type: ID

Usage

The nickname field is required for the user sObject when using the createPortalUser method.

Note
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.

forgotPassword(String)

Resets the user's password and sends an email to the user with their new password. Returns a value indicating whether the password reset was successful or not.

Signature

public static Boolean forgotPassword(String username)

Parameters

username
Type: String

Return Value

Type: Boolean

Note
The return value will always be true unless it’s called outside of a Visualforce page. If it's called outside of a Visualforce page, it will be false.

Usage

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.

getAdminEmail()

Returns the email address of the site administrator.

Signature

public static String getAdminEmail()

Return Value

Type: String

getAdminId()

Returns the user ID of the site administrator.

Signature

public static ID getAdminId()

Return Value

Type: ID

getAnalyticsTrackingCode()

The tracking code associated with your site. This code can be used by services like Google Analytics to track page request data for your site.

Signature

public static String getAnalyticsTrackingCode()

Return Value

Type: String

getCurrentSiteUrl()

Deprecated. This method was replaced by getBaseUrl() in API version 30.0. Returns the base URL of the current site that references and links should use.

Signature

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()

Return Value

Type: String

Usage

Use getBaseUrl() instead.

getBaseCustomUrl()

Returns a base URL for the current site that doesn’t use a Force.com subdomain. The returned URL uses the same protocol (HTTP or HTTPS) as the current request if at least one non-Force.com custom URL that supports HTTPS exists on the site. The returned value never ends with a / character. If all the custom URLs in this site end in Force.com or this site has no custom URLs, then this returns an empty string. If the current request is not a site request, then this method returns an empty string. This method replaced getCustomWebAddress and includes the custom URL's path prefix..

Signature

public static String getBaseCustomUrl()

Return Value

Type: String

Usage

This method replaces getCustomWebAddress() and includes the custom URL's path prefix.

getBaseInsecureUrl()

Returns a base URL for the current site that uses HTTP instead of HTTPS. The current request's domain is used. The returned value includes the path prefix and never ends with a / character. If the current request is not a site request, then this method returns an empty string.

Signature

public static String getBaseInsecureUrl()

Return Value

Type: String

getBaseRequestUrl()

Returns the base URL of the current site for the requested URL. This isn't influenced by the referring page's URL. The returned URL uses the same protocol (HTTP or HTTPS) as the current request. The returned value includes the path prefix and never ends with a / character. If the current request is not a site request, then this method returns an empty string.

Signature

public static String getBaseRequestUrl()

Return Value

Type: String

getBaseSecureUrl()

Returns a base URL for the current site that uses HTTPS instead of HTTP. The current request's domain is preferred if it supports HTTPS. Domains that are not Force.com subdomains are preferred over Force.com subdomains. A Force.com subdomain, if associated with the site, is used if no other HTTPS domains exist in the current site. If no HTTPS custom URLs exist in the site, then this method returns an empty string. The returned value includes the path prefix and never ends with a / character. If the current request is not a site request, then this method returns an empty string.

Signature

public static String getBaseSecureUrl()

Return Value

Type: String

getBaseUrl()

Returns the base URL of the current site that references and links should use. Note that this field may return the referring page's URL instead of the current request's URL. The returned value includes the path prefix and never ends with a / character. If the current request is not a site request, then this field returns an empty string. This field replaces getCurrentSiteUrl.

Signature

public static String getBaseUrl()

Return Value

Type: String

Usage

This method replaces getCurrentSiteUrl().

getCustomWebAddress()

Deprecated. This method was replaced by getBaseCustomUrl() in API version 30.0.

Signature

Returns the request's custom URL if it doesn't end in Force.com 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()

Return Value

Type: String

Usage

Use getBaseCustomUrl() instead.

getDomain()

Returns the Force.com domain name for your organization.

Signature

public static String getDomain()

Return Value

Type: String

getErrorDescription()

Returns the error description for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string.

Signature

public static String getErrorDescription()

Return Value

Type: String

getErrorMessage()

Returns an error message for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string.

Signature

public static String getErrorMessage()

Return Value

Type: String

getMasterLabel()

Returns the value of the Master Label field for the current site. If the current request is not a site request, then this field returns null.

Signature

public static String getMasterLabel()

Return Value

Type: String

getName()

Returns the API name of the current site.

Signature

public static String getName()

Return Value

Type: String

getOriginalUrl()

Returns the original URL for this page if it’s a designated error page for the site; otherwise, returns null.

Signature

public static String getOriginalUrl()

Return Value

Type: String

getPathPrefix()

Returns the URL path prefix of the current site or an empty string if none. For example, if the requested site URL is http://myco.force.com/partners, then /partners is the path prefix. If the current request is not a site request, then this method returns an empty string. This method replaced getPrefix in API version 30.0.

Signature

public static String getPathPrefix()

Return Value

Type: String

getPrefix()

Deprecated. This method was replaced by getPathPrefix() in API version 30.0.

Signature

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()

Return Value

Type: String

getSiteId()

Returns the ID of the current site. If the current request is not a site request, then this field returns null.

Signature

public static String getSiteId()

Return Value

Type: Id

getTemplate()

Returns the template name associated with the current site; returns the default template if no template has been designated.

Signature

public static System.PageReference getTemplate()

Return Value

Type: System.PageReference

getSiteType()

Returns the API value of the site type field for the current site. This can be Visualforce for a Force.com site, Siteforce for a Site.com site, ChatterNetwork for a Force.com Communities site, or ChatterNetworkPicasso for a Site.com Communities site. If the current request is not a site request, then this method returns null.

Signature

public static String getSiteType()

Return Value

Type: String

getSiteTypeLabel()

Returns the value of the Site Type field's label for the current site. If the current request is not a site request, then this method returns null.

Signature

public static String getSyteTypeLabel()

Return Value

Type: String

isLoginEnabled()

Returns true if the current site is associated with an active login-enabled portal; otherwise returns false.

Signature

public static Boolean isLoginEnabled()

Return Value

Type: Boolean

isPasswordExpired()

For authenticated users, returns true if the currently logged-in user's password is expired. For non-authenticated users, returns false.

Signature

public static Boolean isPasswordExpired()

Return Value

Type: Boolean

isRegistrationEnabled()

Returns true if the current site is associated with an active self-registration-enabled Customer Portal; otherwise returns false.

Signature

public static Boolean isRegistrationEnabled()

Return Value

Type: Boolean

login(String, String, String)

Allows users to log in to the current site with the given username and password, then takes them to the startUrl. If startUrl is not a relative path, it defaults to the site's designated index page.

Signature

public static System.PageReference login(String username, String password, String startUrl)

Parameters

username
Type: String
password
Type: String
startUrl
Type: String

Return Value

Type: System.PageReference

Usage

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.

Note
Do not include http:// or https:// in the startURL.

setPortalUserAsAuthProvider(sObject, String)

Sets the specified user information within the site’s portal via an authentication provider.

Signature

public static Void setPortalUserAsAuthProvider(sObject user, String contactId)

Parameters

user
Type: sObject
contactId
Type: String

Return Value

Type: Void

Usage

  • 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.
  • For more information on an authentication provider, see RegistrationHandler.
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.