Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Reference Apex Classes

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;

657
Reference Apex Classes

}
}

/**
* 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 SiteRegisterController Apex 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);

658
Reference Cookie Class

with

String ownerId = OWNER_ID;


String userId = Site.createPersonAccountPortalUser(u, ownerId, password);

Cookie Class
The Cookie class lets you access cookies for your Force.com site using fApex.
Use the setCookies method of the pageReference class to attach cookies to a page.

Important:

• Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent
sign and their hexadecimal representation.
• The setCookies method adds the prefix “apex__” to the cookie names.
• Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute.
• After you create a cookie, the properties of the cookie can't be changed.
• Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use
a cookie value to generate dynamic content, you should disable page caching. For more information, see “Caching
Force.com Sites Pages” in the Salesforce online help.

Consider the following limitations when using the Cookie class:

• The Cookie class can only be accessed using Apex that is saved using the Salesforce.com API version 19 and above.
• The maximum number of cookies that can be set per Force.com domain depends on your browser. Newer browsers have
higher limits than older ones.
• Cookies must be less than 4K, including name and attributes.

The following are the instance methods for the Cookie class, which is part of Force.com sites.

Name Arguments Return Type Description


getDomain String Returns the name of the server
making the request.
getMaxAge Integer Returns a number representing how
long the cookie is valid for, in
seconds. If set to < 0, a session
cookie is issued. If set to 0, the cookie
is deleted.
getName String Returns the name of the cookie. Can't
be null.
getPath String Returns the path from which you can
retrieve the cookie. If null or blank,
the location is set to root, or “/”.
getValue String Returns the data captured in the
cookie, such as Session ID.

659
Reference Apex Classes

Name Arguments Return Type Description


isSecure Boolean Returns true if the cookie can only
be accessed through HTTPS,
otherwise returns false.

For more information on sites, see “Force.com Sites Overview” in the Salesforce online help.
The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to
update a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie.

// A Visualforce controller class that creates a cookie


// used to keep track of how often a user displays a page
public class CookieController {

public CookieController() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');

// If this is the first time the user is accessing the page,


// create a new cookie with name 'counter', an initial value of '1',
// path 'null', maxAge '-1', and isSecure 'false'.
if (counter == null) {
counter = new Cookie('counter','1',null,-1,false);
} else {
// If this isn't the first time the user is accessing the page
// create a new cookie, incrementing the value of the original count by 1
Integer count = Integer.valueOf(counter.getValue());
counter = new Cookie('counter', String.valueOf(count+1),null,-1,false);
}

// Set the new cookie for the page


ApexPages.currentPage().setCookies(new Cookie[]{counter});
}

// This method is used by the Visualforce action {!count} to display the current
// value of the number of times a user had displayed a page.
// This value is stored in the cookie.
public String getCount() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
if(counter == null) {
return '0';
}
return counter.getValue();
}
}

// Test class for the Visualforce controller


@isTest
private class CookieControllerTest {
// Test method for verifying the positive test case
static testMethod void testCounter() {
//first page view
CookieController controller = new CookieController();
System.assert(controller.getCount() == '1');

//second page view


controller = new CookieController();
System.assert(controller.getCount() == '2');
}
}

660
Reference Visualforce Classes

The following is the Visualforce page that uses the CookieController Apex controller above. The action {!count} calls
the getCount method in the controller above.

<apex:page controller="CookieController">
You have seen this page {!count} times
</apex:page>

Visualforce Classes
In addition to giving developers the ability to add business logic to Salesforce system events such as button clicks and related
record updates, Apex can also be used to provide custom logic for Visualforce pages through custom Visualforce controllers
and controller extensions:

• A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller.
If you use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any
functionality that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions
of the current user are ignored. You can specify whether a user can execute methods in a custom controller based on the
user's profile.
• A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller.
Extensions allow you to leverage the functionality of another controller while adding your own custom logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the
current user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions.
Although the extension class executes in system mode, the standard controller executes in user mode. As with custom
controllers, you can specify whether a user can execute methods in a controller extension based on the user's profile.

This section includes information about the system-supplied Apex classes that can be used when building custom Visualforce
controllers and controller extensions. In addition to these classes, the transient keyword can be used when declaring methods
in controllers and controller extensions. For more information, see Using the transient Keyword on page 148.
For more information on Visualforce, see the Visualforce Developer's Guide.

Action Class
You can use ApexPages.Action to create an action method that you can use in a Visualforce custom controller or controller
extension. For example, you could create a saveOver method on a controller extension that performs a custom save.

Instantiation
The following code snippet illustrates how to instantiate a new ApexPages.Action object that uses the save action:

ApexPages.Action saveAction = new ApexPages.Action('{!save}');

Methods
The action methods are all called by and operate on a particular instance of Action.
The table below describes the instance methods for Action.

661

You might also like