UI Flashcards

1
Q

Create Visualforce Pages

A
  • Create Visualforce Pages in the Developer Console
  • Create a page using the “quick fix” tool available in Visualforce development mode:

In your browser, enter a URL in the following form: https://yourSalesforceOrgURL/apex/nameOfNewPage, where the value of yourSalesforceOrgURL is the URL used to access your Salesforce org (for example, MyDomainName.my.salesforce.com) and the value of nameOfNewPage is the value you want to give to the Name field on your page definition (example - https://MyDomainName.my.salesforce.com/apex/HelloWorld)
Page names can’t be longer than 40 characters.
Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create page nameOfNewPage to create the new page. Both the page Name and Label are assigned the nameOfNewPage value you specified in the URL.

  • Create Pages in Setup:
    From Setup, enter Visualforce Pages, then select Visualforce Pages.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

View created Visualforce Page

A

Once your page has been created, you can access it by clicking Preview (Setup > Visualforce Pages). You can also view it manually by entering a URL in the following form: http://yourSalesforceOrgURL/apex/nameOfNewPage, where the value of yourSalesforceOrgURL is your Salesforce organization’s URL (for example, MyDomainName.my.salesforce.com) and the value of nameOfNewPage is the value of the Name field on your page definition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Enable Visualforce Development Mode

A

Development mode provides you with:

A special development footer on every Visualforce page that includes the page’s view state, any associated controller, a link to the component reference documentation, and a page markup editor that offers highlighting, find-replace functionality, and auto-suggest for component tag and attribute names.
The ability to define new Visualforce pages just by entering a unique URL.
Error messages that include more detailed stack traces than what standard users receive.
Enable Visualforce Development Mode:
User Profile (Personal settings) > My Personal Information > Advanced User Details: Development Mode checkbox, Show View State in Development Mode checkbox
Show View State in Development Mode checkbox enables the View State tab on the development footer. This tab is useful for monitoring the performance of your Visualforce pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Customization of Visualforce integration into Lightning

A

In Salesforce Classic, the default value of the sidebar attribute and showHeader attribute is true. However, in Lightning Experience and the Salesforce mobile app, the value of these attributes is overridden and is always false. There’s no way to suppress the Lightning Experience header.

The page still includes some Salesforce style sheets, which let you match Salesforce choices for fonts, size, and so on. To suppress all Salesforce output, add standardStylesheets=”false” to remove the styles as well.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Visualforce Expressions

A

Dynamic data is accessed in markup through the use of global variables, calculations, and properties made available by the page’s controller. Together these are described generally as Visualforce expressions. Use expressions for dynamic output or passing values into components by assigning them to attributes.

A Visualforce expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. Method calls aren’t allowed in expressions.

The expression syntax in Visualforce is:** {! expression }**
The resulting value can be a primitive (integer, string, and so on), a Boolean, an sObject, a controller method such as an action method, and other useful results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Visualforce Global Variables

A

{! $GlobalName.fieldName }
Use global variables to access and display system values and resources in your Visualforce markup.

For example, Visualforce provides information about the logged-in user in a global variable called $User: {! $GlobalName.fieldName }.
Example:
{!$User.FirstName } {!$User.LastName } {! $User.Username }

Visualforce expressions are case-insensitive, and spaces within the {! … }are ignored. So these expressions all produce the same value:

{!$User.FirstName} {!$USER.FIRSTNAME} {!$user.firstname }

There are nearly two dozen global variables that can be used within Visualforce. They’re useful for getting information about the currently logged in user, as you saw, but also for getting details about the organization ( $Organization), settings ( $Setup), details about custom objects ( $ObjectType), actions available on those objects ( $Action), and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Visualforce Formula Expressions

A

Examples: {!$User.FirstName & ‘ ‘ & $User.LastName}
{! TODAY() + 7}

<p>Tomorrow will be day number {! DAY(TODAY() + 1) }</p>

<p>Let's find a maximum: {! MAX(1,2,3,4,5,6,5,4,3,2,1) } </p>

<p>The square root of 49 is {! SQRT(49) }</p>

<p>Is it true? {! CONTAINS('salesforce.com', 'force.com') }</p>

<p>The year today is {! YEAR(TODAY()) }</p>

Visualforce supports formulas that let you manipulate values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Visualforce Conditional Expressions

A

Use a conditional expression to display different information based on the value of the expression.
You can do this in Visualforce by using a conditional formula expression, such as IF(). The IF()expression takes three arguments.
Example:

<p>{! IF( CONTAINS('salesforce.com','force.com'), 'Yep', 'Nope') }</p>

<p>{! IF( DAY(TODAY()) < 15, 'Before the 15th', 'The 15th or after') }</p>

({! IF($User.isActive, $User.Username, ‘inactive’) })

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Visualforce: Accessing Data with a Standard Controller

A

Every standard controller includes a getter method that returns the record specified by the id query string parameter in the page URL. This method allows the associated page markup to reference fields on the context record by using {!object} syntax, where object is the lowercase name of the object associated with the controller. For example, a page that uses the Account standard controller can use {!account.name} to return the value of the name field on the account that is currently in context.

For the getter method to succeed, the record specified by the id query string parameter in the URL must be of the same type as the standard controller. For example, a page that uses the Account standard controller can only return an account record.

As with queries in the Lightning Platform API, you can use merge field syntax to retrieve data from related records:
You can traverse up to five levels of child-to-parent relationships. For example, if using the Contact standard controller, you can use {!contact.Account.Owner.FirstName} (a three-level child-to-parent relationship) to return the name of the owner of the account record that is associated with the contact.
You can traverse one level of parent-to-child relationships. For example, if using the Account standard controller, you can use {!account.Contacts} to return an array of all contacts associated with the account that is currently in context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Visualforce: Associating a Standard Controller with a Visualforce Page

A

To associate a standard controller with a Visualforce page, use the standardController attribute on the <apex:page> tag and assign it the name of any Salesforce object that can be queried using the Lightning Platform API.</apex:page>

For example, to associate a page with the standard controller for a custom object named MyCustomObject, use the following markup:

<apex:page>
</apex:page>

When you use the standardController attribute on the <apex:page> tag, you cannot use the controller attribute at the same time.</apex:page>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Visualforce: Using Standard Controller Actions

A

Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard controllers. You can associate these actions with any Visualforce component that includes an action attribute.
**save, quicksave, edit, delete, cancel, list**

For example, the following page allows you to update an account. When you click Save, the save action is triggered on the standard controller, and the account is updated.
<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockSection>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Command buttons and links that are associated with save, quicksave, edit, or delete actions in a standard controller are only rendered if the user has the appropriate permissions. Likewise, if no particular record is associated with a page, command buttons and links associated with the edit and delete actions are not rendered.
</apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Visualforce: Validation Rules and Standard Controllers

A

If a user enters data on a Visualforce page that uses a standard controller, and that data causes a validation rule error, the error can be displayed on the Visualforce page. If the validation rule error location is a field associated with an <apex:inputField> component, the error displays there. If the validation rule error location is set to the top of the page, use the <apex:pageMessages> or <apex:messages> component within the <apex:page> to display the error.</apex:page></apex:messages></apex:pageMessages></apex:inputField>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Visualforce: Styling Pages that Use Standard Controllers

A

Any page associated with a standard controller automatically inherits the style that is used for standard Salesforce pages associated with the specified object.
You can override the styling of a page that uses a standard controller with the tabStyle attribute on the <apex:page> tag. For example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses the Opportunity tab's yellow coloring:</apex:page>

<apex:page>
</apex:page>

To use the styling associated with MyCustomObject:

<apex:page>
</apex:page>

To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use:

<apex:page>
</apex:page>

Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Visualforce: Checking for Object Accessibility

A

If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated with the controller.

You can check for the accessibility of an object like this:
{!$ObjectType.objectname.accessible}
This expression returns a true or false value.
For example, to check if you have access to the standard Lead object, use the following code:
{!$ObjectType.Lead.accessible}
For custom objects, the code is similar:
{!$ObjectType.MyCustomObjectc.accessible}

To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For example, to display a page block if a user has access to the Lead object, you would do the following:

<apex:page>
<apex:pageBlock>
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
</apex:page>

It is good practice to provide an alternative message if a user cannot access an object. For example:

<apex:page>
<apex:pageBlock>
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
<apex:pageBlock>
<p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p>
</apex:pageBlock>
</apex:page>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Visualforce: Standard List Controllers

A

Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce pages that work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with the following objects:
Account
Asset
Campaign
Case
Contact
Contract
Idea
Lead
Opportunity
Order
Product2
Solution
User
Custom objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Visualforce: Associating a Standard List Controller with a Visualforce Page

A

Using a standard list controller is very similar to using a standard controller. First you set the standardController attribute on the <apex:page> component, then you set the recordSetVar attribute on the same component.
**<apex:page>**</apex:page></apex:page>

When you use the standardController attribute on the <apex:page> tag, you can’t use the controller attribute at the same time.</apex:page>

The recordSetVar attribute not only indicates that the page uses a list controller, it sets the variable name of the record collection. This variable can be used to access data in the record collection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Visualforce: List View - Access Records with Expression Syntax

A

When using a standard list controller, the returned records automatically sort on the first column of data defined by the current view. When using an extension or custom list controller, you can control the sort method.
As with queries in the Lightning Platform API, you can use expression language syntax to retrieve data from related records. As with standard controllers, you can traverse up to five levels of child-to-parent relationships and one level of parent-to-child relationships.

<apex:page>
<apex:pageBlock>
<apex:pageBlockTable>
<apex:column></apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

17
Q

Visualforce: List View - Access Records with IDs

A

In a typical page interaction, a user selects records from a listview before navigating to a page, and Visualforce sends them to the controller. You can also specify records manually by setting selected records directly on to the controller.

The standard list controller is based on the StandardSetController Apex class. Use the method ApexPages.StandardSetController.setSelected() to set the list of records from your Apex controller.
*public with sharing class MyControllerExtension {
private ApexPages.StandardSetController setController;

public MyControllerExtension(ApexPages.StandardSetController setController) {
    this.setController = setController;
    
    Account [] records = [SELECT Id, Name FROM Account LIMIT 30];
    setController.setSelected(records);
} }* The standard list controller is based on the StandardSetController Apex class. To retrieve a list of records assigned to the list controller, use the method ApexPages.StandardSetController.setSelected().

In the MyControllerExtension’s constructor, make a SOQL request to select the ID and Name from the Account object and limit the first 30 results. Then, definesetController.setSelected(records) so that the records are selected on page load.
A standard list controller can return up to 10,000 records. Custom controllers can work with larger results sets.

It’s also possible to pass a list of record IDs into a URL by including them as multiple query parameters. For example, a URL that has three Account IDs looks like: /apex/pageName?ids=001xx00account1&ids=001xx00account2&ids=001xx00account3.

Some browsers have a hard limit on the length of a URL. If your URL has too many IDs, then there is a greater chance of reaching that limit, causing your page to misbehave. Instead of manually including IDs in a URL string, it’s better to set the selected records on to the controller.

18
Q

Visualforce: Standard List Controller Actions

A

Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
Actions: save, quicksave, list, cancel,
for page navigations - first, last, next, previous
Example:
*<apex:page>
<apex:form>
<apex:selectList>
<apex:selectOptions></apex:selectOptions>
</apex:selectList>
<apex:commandButton></apex:commandButton>
</apex:form>
</apex:page>*
</apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

19
Q

Visualforce: List View - Pagination

A

By default, a list controller returns 20 records on the page. To control the number of records displayed on each page, use a controller extension to set the pageSize.

<apex:page>
<apex:pageBlock>
<apex:form>
<apex:pageBlockSection>
<apex:dataList>
{!a.name}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid>
<apex:commandLink>Previous</apex:commandlink>
<apex:commandLink>Next</apex:commandlink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>
</apex:commandLink></apex:commandLink></apex:panelGrid></apex:form></apex:pageBlock></apex:page>

20
Q

Visualforce: Using List Views with Standard List Controllers - Filter

A

Many Salesforce pages include list views that allow you to filter the records displayed on the page. For example, on the opportunities home page, you can choose to view a list of only the opportunities you own by selecting My Opportunities from the list view drop-down. On a page that is associated with a list controller, you can also use list views.

For example, to create a simple list of accounts with a list view, create a page with the following markup:

<apex:page>
<apex:pageBlock>
<apex:form>
<apex:panelGrid>
<apex:outputLabel></apex:outputLabel>
<apex:selectList>
<apex:actionSupport></apex:actionSupport>
<apex:selectOptions></apex:selectOptions>
</apex:selectList>
</apex:panelGrid>
<apex:pageBlockSection>
<apex:dataList>
{!a.name}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

This page is associated with the standard account controller and the <apex:selectlist> component is populated by {!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down list, it is bound to the filterId property for the controller. When the filterId is changed, the records available to the page changes, so, when the <apex:datalist> is updated, that value is used to update the list of records available to the page.</apex:datalist></apex:selectlist>

21
Q

Visualforce: Editing Records with List Controllers

A

You can edit a set of records using list controllers, too. For example, if you create a page with the following markup:

<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageMessages></apex:pageMessages>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockTable>
<apex:column></apex:column>
<apex:column>
<apex:inputField></apex:inputField>
</apex:column>
<apex:column>
<apex:inputField></apex:inputField>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

(you see a page that allows you to update and save the Stage and Close Date on your opportunities)
Command buttons and links that are associated with save, quicksave, or edit actions in a list controller are not rendered if the user does not have the appropriate permissions. Likewise if no particular record is associated with a page, command buttons and links associated with the edit actions are not rendered.

22
Q

Visualforce: Standard Controller - Display Fields from Related Records

A

Use dot notation to display data from related records.

For example, while viewing the object details for Account, you might have noticed that the Account object has a field called Account Owner, and that its type is Lookup(User). In other words, this field has a relationship to a User record. By clicking the Account Owner field label link, you’ll discover its Field Name is Owner.

The Owner relationship represents a User. And, if from Setup you go to Object Manager | User | Fields & Relationships, you’ll find that User has a Name field. Let’s use this information to display it.

In the body of the page, before the account name, add the following line.

Account owner: {! Account.Owner.Name } <br></br>
The dot notation ( Account.Owner.Name) indicates that you want to traverse the relationship between the records. You know that Account.Owner indicates the Owner field of the account record. The extra Name at the end indicates that the owner field isn’t a simple field representing a string, but a relationship to another record (it’s a Lookup(User)), and that you’d like to get the record represented by the value of the Owner field (it’s a User record), and display the Name field on that record.

23
Q

Visualforce - Display Individual Fields

A

Use <apex:outputField> to display individual fields from a record.</apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

The four fields are added to the page. But the formatting perhaps isn’t what you expected. The field values are displayed all on one line, without labels, and without other formatting. That’s not what we want, and it’s quite a contrast to the <apex:detail> and <apex:relatedList> components, which automatically use the platform styling. By itself, the <apex:outputField> only outputs the field’s value. But when you wrap it in <apex:pageBlock> and <apex:pageBlockSection> components, its behavior changes quite a bit.
Wrap the <apex:outputField> lines with <apex:pageBlock> and <apex:pageBlockSection>components, so that your markup looks like this.</apex:pageBlockSection></apex:pageBlock></apex:outputField></apex:pageBlockSection></apex:pageBlock></apex:outputField></apex:relatedList></apex:detail>

24
Q

Visualforce: controller extension

A

A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
You want to add new actions.
You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.

Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition. For information, see “Using the with sharing, without sharing, and inherited sharing Keywords”

25
Q

Visualforce: custom controller

A

A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.

26
Q

Visualforce: Building a Custom Controller

A

A custom controller is an Apex class that uses the default, no-argument constructor for the outer, top-level class. You cannot create a custom controller constructor that includes parameters.

To create a custom controller:
Create new Apex Class.
public class MyController {

private final Account account;

public MyController() {
    account = [SELECT Id, Name, Site FROM Account 
               WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
}

public Account getAccount() {
    return account;
}

public PageReference save() {
    update account;
    return null;
} } The following Visualforce markup shows how the custom controller above can be used in a page:

<apex:page>
<apex:form>
<apex:pageBlock>
You belong to Account Name: <apex:inputField></apex:inputField>
<apex:commandButton></apex:commandButton>
</apex:pageBlock>
</apex:form>
</apex:page>

The custom controller is associated with the page because of the controller attribute of the <apex:page> component.</apex:page>

As with standard controllers and controller extensions, custom controller methods can be referenced with {! } notation in the associated page markup. In the example above, the getAccount method is referenced by the <apex:inputField> tag's value attribute, while the <apex:commandButton> tag references the save method with its action attribute.</apex:commandButton></apex:inputField>

Like other Apex classes, all custom controllers run in system mode. Consequently, the current user’s credentials are not used to execute controller logic, and the user’s permissions and field-level security do not apply.

You can choose whether a custom controller respects a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

A custom controller can also be used to create new records. For example:

public class NewAndExistingController {

public Account account { get; private set; }

public NewAndExistingController() {
    Id id = ApexPages.currentPage().getParameters().get('id');
    account = (id == null) ? new Account() : 
        [SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
}

public PageReference save() {
    try {
        upsert(account);
    } catch(System.DMLException e) {
        ApexPages.addMessages(e);
        return null;
    }
    //  After successful Save, navigate to the default view page
    PageReference redirectSuccess = new ApexPages.StandardController(Account).view();
    return (redirectSuccess);
} } The following Visualforce markup shows how the custom controller above can be used in a page:

<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageMessages></apex:pageMessages>
<apex:pageBlockSection>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

27
Q

Visualforce: Building a Controller Extension

A

A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, where CustomControllerName is the name of a custom controller you want to extend.

The following class is a simple example of a controller extension:

public class myControllerExtension {

private final Account acct;

// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public myControllerExtension(ApexPages.StandardController stdController) {
    this.acct = (Account)stdController.getRecord();
}

public String getGreeting() {
    return 'Hello ' + acct.name + ' (' + acct.id + ')';
} } The following Visualforce markup shows how the controller extension from above can be used in a page:

<apex:page>
{!greeting} <p></p>
<apex:form>
<apex:inputField></apex:inputField> <p></p>
<apex:commandButton></apex:commandButton>
</apex:form>
</apex:page>

The extension is associated with the page using the extensions attribute of the <apex:page> component.</apex:page>

As with all controller methods, controller extension methods can be referenced with {! } notation in page markup. In the example above, the {!greeting} expression at the top of the page references the controller extension’s getGreeting method.

Because this extension works in conjunction with the Account standard controller, the standard controller methods are also available. For example, the value attribute in the <apex:inputField> tag retrieves the name of the account using standard controller functionality. Likewise, the <apex:commandButton> tag references the standard account save method with its action attribute.</apex:commandButton></apex:inputField>

Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods with the same name. For example, if the following page exists:

<apex:page>
<apex:outputText></apex:outputText>
</apex:page>

with the following extensions:
public class ExtOne {
public ExtOne(ApexPages.StandardController acon) { }

public String getFoo() {
    return 'foo-One';
} } public class ExtTwo {
public ExtTwo(ApexPages.StandardController acon) { }

public String getFoo() {
    return 'foo-Two';
} } The value of the <apex:outputText> component renders as foo-One. Overrides are defined by whichever methods are defined in the “leftmost” extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is overriding the method of ExtTwo.

Like other Apex classes, controller extensions run in system mode. Consequently, the current user’s credentials are not used to execute controller logic, and the user’s permissions and field-level security do not apply. However, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which the permissions, field-level security, and sharing rules of the current user apply.

You can choose whether a controller extension respects a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

28
Q

Visualforce: Controller Methods

A

Visualforce markup can use the following types of controller extension and custom controller methods:
Action
Getter
Setter
Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
For example, in the sample page in Building a Custom Controller, the controller's save method is called by the action parameter of the <apex:commandButton> tag.
**Getter Methods**
Getter methods return values from a controller. Every value that is calculated by a controller and displayed in a page must have a corresponding getter method, including any Boolean variables. For example, in the sample page in Building a Custom Controller, the controller includes a getAccount method. This method allows the page markup to reference the account member variable in the controller class with {! } notation. The value parameter of the <apex:inputField> tag uses this notation to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable.

Important

It’s a best practice for getter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which getter methods are called, or how many times they might be called in the course of processing a request. Design your getter methods to produce the same outcome, whether they are called once or multiple times for a single page request.

**Setter Methods**
Setter methods pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed before any action methods.

For example, the following markup displays a page that implements basic search functionality for Leads. The associated controller includes getter and setter methods for the search box input, and then uses the search text to issue a SOSL query when the user clicks Go!. Although the markup doesn’t explicitly call the search text setter method, it executes before the doSearch action method when a user clicks the command button.
While a getter method is always required to access values from a controller, it’s not always necessary to include a setter method to pass values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's fields are automatically set if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior is shown in the sample page in Building a Custom Controller.

Setter methods must always be named setVariable.

Important

It’s a best practice for setter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which setter methods are called, or how many times they might be called in the course of processing a request. Design your setter methods to produce the same outcome, whether they are called once or multiple times for a single page request.
</apex:inputField></apex:commandButton></apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

29
Q

Visualforce: Controller Class Security

A

Like other Apex classes, you can specify whether a user can execute methods in a custom controller or controller extension class based on the user’s profile.

If you’ve installed a managed package in your org, you can set security only for the Apex classes in the package that are declared as global or for classes that contain methods declared as webService.

If users have the Author Apex permission, they can access all Apex classes in the associated organization, regardless of the security settings for individual classes.

Permission for an Apex class is checked only at the top level. For example, class A calls class B. User X has a profile that can access class A but not class B. User X can execute the code in class B, but only through class A; user X cannot invoke class B directly. Likewise, if a Visualforce page uses a custom component with an associated controller, security is only checked for the controller associated with the page. The controller associated with the custom component executes regardless of permissions.

To set Apex class security from the class list page:

From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Next to the name of the class that you want to restrict, click Security.
Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
Click Save.
To set Apex class security from the class detail page:

From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Click the name of the class that you want to restrict.
Click Security.
Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
Click Save.

30
Q

Visualforce custom controllers limits, Large Sets of Data

A

Visualforce custom controllers and controller extensions are subject to Apex governor limits. Additionally, Visualforce iteration components, such as <apex:pageBlockTable> and <apex:repeat>, are limited to a maximum of 1,000 items in the collection they iterate over.</apex:repeat></apex:pageBlockTable>

Sometimes your Visualforce pages may need to work with or display larger sets of data, but not need to make modifications to that data; for example, if you are providing custom reporting and analytics. Visualforce offers developers a “read-only mode”, which relaxes the limit on the number of rows which can be queried in one request, and increases the limit on the number of collection items which can be iterated over within the page.

You can specify read-only mode either for an entire page or, with certain limitations, on individual components or methods.

You can only iterate over large sets of data if you specify read-only mode for the entire page.

Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed to allow querying up to 1,000,000 rows.

In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that can be iterated over using components such as <apex:dataTable>, <apex:dataList>, and <apex:repeat>. This limit increased from 1,000 items to 10,000.</apex:repeat></apex:dataList></apex:dataTable>

31
Q

Visualforce: Setting Read-Only Mode for an Entire Page

A

To enable read-only mode for an entire page, set the readOnly attribute on the <apex:page> component to true.
For example, here is a simple page that will be processed in read-only mode:</apex:page>

<apex:page>
<p>Here is a statistic: {!veryLargeSummaryStat}</p>
</apex:page>

While Visualforce pages that use read-only mode for the entire page can’t use data manipulation language (DML) operations, they can call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only queries, and so on.

32
Q

Visualforce: Setting Read-Only Mode for Controller Methods

A

Visualforce controller methods can, with some important limitations, use the Apex ReadOnly annotation, even if the page itself isn’t in read-only mode.
Visualforce controller methods with the @ReadOnly annotation automatically take advantage of read-only mode. However, restrictions on the @ReadOnly annotation means that, for Visualforce controller methods, a read-only method must also have the @RemoteAction annotation. The @RemoteAction annotation requires that the method be:
Either global or public
static
Enabling read-only mode by using the @ReadOnly annotation must be done on the top level method call. If the top level method call doesn’t have the@ReadOnly annotation, the normal restrictions on maximum queried rows are enforced for the entire request, even if secondary methods are annotated with @ReadOnly.

Using the @ReadOnly annotation on a controller method allows you to retrieve a larger collection of records as the result of a Visualforce expression. However, it doesn’t increase the maximum number of items in a collection for iteration components. If you want to iterate over larger collections of results, you need to enable read-only mode for the entire page.

33
Q

Considerations for Creating Custom Controllers and Controller Extensions

A

Note the following considerations when creating controller extensions and custom controllers:
* Unless a class has a method defined as webService, custom extension and controller classes and methods are generally defined as public. If a class includes a web service method, it must be defined as global.
* Use sets, maps, or lists when returning data from the database. This makes your code more efficient because the code makes fewer trips to the database.
* The Apex governor limits for Visualforce controller extensions and custom controllers are the same as the limits for anonymous block or WSDL methods.
* If you are building a custom controller or controller extension, be careful that you do not inadvertently expose sensitive data that would normally be hidden from users. Consider using the with sharing keywords on class definitions to enforce permissions. Also be careful using Web services, which are secured as top-level entry points by the profile, but execute in the system context once they are initiated.
* Apex methods and variables are not instantiated in a guaranteed order.
* You can’t use data manipulation language (DML) operations in a “getxxx” method in a controller.
* You can’t use data manipulation language (DML) operations in a constructor method in a controller.
* You can’t use the @future annotation in a “getxxx” or “setxxx” method in a controller, or in the constructor for a controller.
* Primitive Apex data types such as String or Integer are passed by value to the component’s controller.
Non-primitive Apex data types such as lists and sObjects are passed by reference to component’s controller. This means that if component’s controller changes the name of an account, the changes are available in page’s controller.
* If your org uses person accounts
When referencing an account record’s name field with a custom controller using the <apex:inputField> component you must specify isPersonAccount in your query. If you create a new account and set name, the record will be a business account. If you create a new account and set lastname, it will be a person account.
As a best practice, create a custom name formula field that will render properly for both person accounts and business accounts, then use that field instead of the standard field in your Visualforce pages.
* If you plan on including your Visualforce page in a Salesforce AppExchange package, in your controller or controller extension, you cannot explicitly reference fields that exist only in a person account.</apex:inputField>

34
Q

Visualforce: Order of Execution in a Visualforce Page

A

When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by the server. The order in which these elements are executed can affect how the page is displayed to the user.

To fully understand the order of execution of elements on a Visualforce page, you must first understand the page’s lifecycle–that is, how the page is created and destroyed during the course of a user session. The lifecycle of a page is determined not just by the content of the page, but also by how the page was requested. There are two types of Visualforce page requests:
A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.
A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action.

35
Q

Visualforce: Order of Execution for Visualforce Page Get Requests

A

A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.
In the diagram above the user initially requests a page, either by entering a URL or clicking a link or button. This initial page request is called the get request.

  • The constructor methods on the associated custom controller or controller extension classes are called, instantiating the controller objects.
  • If the page contains any custom components, they are created and the constructor methods on any associated custom controllers or controller extensions are executed. If attributes are set on the custom component using expressions, the expressions are evaluated after the constructors are evaluated.
  • The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method calls, such as getting or setting a property value, are made.</apex:page>
  • If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.</apex:form>
  • The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser executes them.

As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods.

Once a new get request is made by the user, the view state and controller objects are deleted.
Note

If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a postback request is made. When a postback request is made, the view state is maintained.

If the user interaction requires a page update, such as when the user clicks a Save button that triggers a save action, a postback request is made. For more information on postback requests, see Order of Execution for Visualforce Page Postback Requests.

36
Q

Visualforce Controllers

UI

A

A developer can either use a standard controller provided by Lightning Platform, or add custom controller logic with a class written in Apex:
A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page. If you use a standard controller on a page and the user doesn’t have access to the object, the page displays an insufficient privileges error message. Resolve this error by checking the user’s accessibility for an object and displaying components appropriately. A standard list controller enables you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce pages that work with a set of records include list pages, related lists, and mass action pages.
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 - with sharing keywords.
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 use the functionality of another controller while adding your own custom logic. 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.

37
Q

What is a Visualforce Page?

UI

A

Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:
Visualforce markup
A Visualforce controller
Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single <apex:page> tag. The markup defines the user interface components that are included on the page, and the way they appear.
**Visualforce Controllers**
A Visualforce controller is a set of instructions for what happens when a user interacts with components specified in associated Visualforce markup. One type of interaction is when a user clicks a button or link. Controllers also provide access to the data displayed in a page, and can modify component behavior.</apex:page>

38
Q

Create Visualforce pages

UI

A

Visualforce is a framework that allows developers to build custom user interfaces that can be hosted natively on Lightning Platform. The Visualforce framework includes a tag-based markup language similar to HTML. It also has a set of server-side “standard controllers” that make basic database operations, such as queries and saves, simple to perform.
Developers create Visualforce pages by composing components, HTML, and optional styling elements. Visualforce can integrate with any standard web technology or JavaScript framework to allow for a more animated and rich user interface.

39
Q

Where Can Visualforce Pages Be Used?

UI

A

Developers can use Visualforce pages to:
Override standard buttons, such as the New button for accounts, or the Edit button for contacts
Override tab overview pages, such as the Accounts tab home page
Define custom tabs
Embed components in detail page layouts
Create dashboard components or custom help pages
Customize, extend, or integrate the sidebars in the Salesforce console (custom console components)
Add navigation menu items and actions in the Salesforce mobile app