# developer Platform - Full Documentation
# (Optional) Step 5: Use the Connector with OAuth Bearer Token Login
You can use the connector with OAuth authentication as an alternative to username and password authentication. This step is optional and requires an OAuth token.
Obtain an OAuth bearer access token for your Salesforce user. You supply this access token in the connector example.
See [Set Up Authorization with OAuth 2.0](https://developer.salesforce.com/docs/platform/api-streaming/guide/code-sample-auth-oauth.md). Also see [Authorize Apps with OAuth](https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm).
Let’s run an example that uses OAuth bearer token login.
1. In the /src/main/java/com/salesforce/emp/connector/example folder, open the [BearerTokenExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/BearerTokenExample.java) Java source file.
2. Run the `BearerTokenExample` class, and provide the following argument values.
Argument
Value
url
URL of the Salesforce instance of the logged-in user
token
The access token returned by the OAuth authentication flow
channel
The channel name for the PushTopic:
/topic/InvoiceStatementUpdates
This quick start is based on a PushTopic event. Alternatively, you can use EMP Connector to listen to any event type. The following lists channel name formats for a sample of streaming events available in the Lightning Platform.
Platform event
For a custom platform event—
/event/EventName__e
For a standard platform event—
/event/EventName
For a custom channel—
/event/ChannelName__chn
Change Data Capture event
For all change events—
/data/ChangeEvents
For a specific standard object—
/data/ObjectNameChangeEvent
For a specific custom object—
/data/CustomObjectName__ChangeEvent
For a custom channel—
/data/ChannelName__chn
PushTopic event
/topic/PushTopicName
Generic event
/u/notifications/GenericStreamingChannel
Optionally, to receive different events, you can include a replay ID as the last argument. Valid values are:
- –1 — Get all new events sent after subscription. This option is the default.
- –2 — Get all new events sent after subscription and all past events within the retention window. Use -2 sparingly. If a large volume of event messages is stored, retrieving all event messages can slow performance.
- Specific number — Get all events that occurred after the event with the specified replay ID.
3. In a browser window, create or modify an invoice statement. After you create or change data that corresponds to the query in your PushTopic, the output looks similar to the following.
```nolang
Subscribed: Subscription [/topic/InvoiceStatementUpdates:-1]
Received:
{event={createdDate=2016-12-12T22:31:48.035Z, replayId=1, type=created}, sobject={Status__c=Open, Id=a070P00000pn0hyQAA, Name=INV-0001, Description__c=blah}}
Received:
{event={createdDate=2016-12-12T22:32:06.440Z, replayId=2, type=updated}, sobject={Status__c=Negotiating, Id=a070P00000pn0hyQAA, Name=INV-0001, Description__c=blah}}
Received:
{event={createdDate=2016-12-12T22:32:57.404Z, replayId=3, type=created}, sobject={Status__c=Open, Id=a070P00000pn0lfQAA, Name=INV-0002, Description__c=Laptops and accessories.}}
```
If you’re listening to another event type, the output would look a bit different. Some events require that you publish the notification instead of Salesforce, such as with platform events.
# \ —Clean Unrendered Body —Clean Unrendered Body
This warning occurs when you change the `isTrue` attribute of an `` tag from `true` to `false` in the same rendering cycle. The unrendered body of the `` must be destroyed, which is avoidable work for the framework that slows down rendering time.
## Example
This component shows the anti-pattern.
```nolang
I am visible
```
Here’s the component’s client-side controller.
```javascript
/* c:ifCleanUnrenderedController.js */
({
init: function(cmp) {
/* Some logic */
cmp.set("v.isVisible", false); // Performance warning trigger
}
})
```
When the component is created, the `isTrue` attribute of the `` tag is evaluated. The value of the `isVisible` attribute is `true` by default so the framework creates the body of the `` tag. After the component is created but before rendering, the `init` event is triggered.
The `init()` function in the client-side controller toggles the `isVisible` value from `true` to `false`. The `isTrue` attribute of the `` tag is now `false` so the framework must destroy the body of the `` tag. This warning displays in the browser console only if you enabled debug mode.
```nolang
WARNING: [Performance degradation] markup://aura:if ["5:0"] in c:ifCleanUnrendered ["3:0"]
needed to clear unrendered body.
```
Click the expand button beside the warning to see a stack trace for the warning.

Click the link for the ifCleanUnrendered entry in the stack trace to see the offending line of code in the Sources pane of the browser console.
## How to Fix the Warning
Reverse the logic for the `isTrue` expression. Instead of setting the `isTrue` attribute to `true` by default, set it to `false`. Set the `isTrue` expression to true in the `init()` method, if needed.
Here’s the fixed component:
```nolang
I am visible
```
Here’s the fixed controller:
```javascript
/* c:ifCleanUnrenderedFixedController.js */
({
init: function(cmp) {
// Some logic
// FIX: set isVisible to true if logic criteria met
cmp.set("v.isVisible", true);
}
})
```
**See Also**
- [*Salesforce Help:* **Enable Debug Mode for Lightning Components**](https://help.salesforce.com/articleView?id=aura_debug_mode.htm)
# \ —Multiple Items Set —Multiple Items Set
This warning occurs when you set the `items` attribute of an `` tag multiple times in the same rendering cycle.
There’s no easy and performant way to check if two collections are the same in JavaScript. Even if the old value of `items` is the same as the new value, the framework deletes and replaces the previously created body of the `` tag.
## Example
This component shows the anti-pattern.
```nolang
{!item}
```
Here’s the component’s client-side controller.
```javascript
/* c:iterationMultipleItemsSetController.js */
({
init: function(cmp) {
var list = cmp.get('v.groceries');
// Some logic
cmp.set('v.groceries', list); // Performance warning trigger
}
})
```
When the component is created, the `items` attribute of the `` tag is set to the default value of the `groceries` attribute. After the component is created but before rendering, the `init` event is triggered.
The `init()` function in the client-side controller sets the `groceries` attribute, which resets the `items` attribute of the `` tag. This warning displays in the browser console only if you enabled debug mode.
```nolang
WARNING: [Performance degradation] markup://aura:iteration [id:5:0] in c:iterationMultipleItemsSet ["3:0"]
had multiple items set in the same Aura cycle.
```
Click the expand button beside the warning to see a stack trace for the warning.

Click the link for the iterationMultipleItemsSet entry in the stack trace to see the offending line of code in the Sources pane of the browser console.
## How to Fix the Warning
Make sure that you don’t modify the `items` attribute of an `` tag multiple times. The easiest solution is to remove the default value for the `groceries` attribute in the markup. Set the value for the `groceries` attribute in the controller instead.
The alternate solution is to create a second attribute whose only purpose is to store the default value. When you’ve completed your logic in the controller, set the `groceries` attribute.
Here’s the fixed component:
```nolang
{!item}
```
Here’s the fixed controller:
```javascript
/* c:iterationMultipleItemsSetFixedController.js */
({
init: function(cmp) {
// FIX (ALTERNATE) if need to set default in markup
// use a different attribute
// var list = cmp.get('v.groceriesDefault');
// FIX: Set the value in code
var list = ['Eggs', 'Bacon', 'Bread'];
// Some logic
cmp.set('v.groceries', list);
}
})
```
**See Also**
- [*Salesforce Help:* **Enable Debug Mode for Lightning Components**](https://help.salesforce.com/articleView?id=aura_debug_mode.htm)
# $A namespace
The `$A` namespace is the entry point for using the framework in JavaScript code.
## Methods
- **[createComponent()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-createcomponent.md)**
Create a component from a type and a set of attributes. This method accepts the name of a type of component, a map of attributes, and a callback to notify the caller.
- **[createComponents()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-createcomponents.md)**
Create an array of components from a list of types and attributes. This method accepts a list of component names and attribute maps, and a callback to notify the caller.
- **[enqueueAction()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-enqueueaction.md)**
Queue a call to an Apex action . The framework queues up actions before sending them to the server. This mechanism is largely transparent to you when you’re writing code but it enables the framework to minimize network traffic by batching multiple actions into one request (XHR).
- **[error()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-error.md)**
Deprecated. For a serious error that has no recovery path, throw a standard JavaScript error instead by using `throw new Error(msg)`.
- **[get()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-get.md)**
Returns a value from the specified global value provider using property syntax.
- **[getCallback()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-getcallback.md)**
Use `$A.getCallback()` to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a `setTimeout()` call. The `$A.getCallback()` call ensures that the framework rerenders the modified component and processes any enqueued actions.
- **[getComponent()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-getcomponent.md)**
Gets an instance of a component from either a global ID or a DOM element that was created by a rendered component.
- **[getReference()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-getreference.md)**
Returns a live reference to the global value requested using property syntax.
- **[getRoot()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-getroot.md)**
Gets the root component or application. For example, `$A.getRoot().get("v.attrName")` returns the value of the `attrName` attribute from the root component.
- **[getToken()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-gettoken.md)**
Returns an application configuration token referenced by name. A tokens file is configured with the `tokens` attribute in the `` tag.
- **[log()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-log.md)**
Deprecated. Logs to the browser's JavaScript console, if it is available. This method doesn't log in production or debug modes so it’s only useful for internal usage by the framework.
- **[reportError()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-reporterror.md)**
Report an error to the server after handling it. Note that the method should be used only if the try-catch mechanism of error handling is not desired or not functional, such as in nested promises.
- **[run()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-run.md)**
Deprecated. Use `getCallback()` instead.
- **[set()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-set.md)**
Sets a value on the specified global value provider using property syntax.
- **[warning()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-warning.md)**
Deprecated. Logs a warning to the browser's JavaScript console, if it is available.
# $Action
A global merge field type to use when referencing standard Salesforce actions, such as displaying the Accounts tab home page, creating accounts, editing accounts, and deleting accounts.
## Usage
Use dot notation to specify an object and an action, for example, `$Action.Account.New`
## Example
The following markup adds a link to create a new account:
```visualforce
Create New Account
```
The following markup adds a link to download an attachment:
```visualforce
Download Now!
```
- **[Valid Values for the $Action Global Variable](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-variables-global-action-valid-values.md)**
The $Action global variable contains a list of actions and objects on which the actions can be performed.
**See Also**
- [Dynamic References to Action Methods Using $Action](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/dynamic-vf/pages-dynamic-vf-globals-action.md)
# $Api
A global merge field type to use when referencing API URLs.
## Usage
Use dot notation to specify an API URL from either the Enterprise or Partner WSDL, or to return the session ID.
**important:** `$Api.Session_ID` and `GETSESSIONID()` return the same value, an identifier for the current session in the current context. This context varies depending on where the global variable or function is evaluated. For example, if you use either in a custom formula field, and that field is displayed on a standard page layout in Salesforce Classic, the referenced session is a basic Salesforce session. That same field (or the underlying variable or formula result), when used in a Visualforce page, references a Visualforce session instead.
Session contexts are based on the domain of the request. That is, the session context changes whenever you cross a hostname boundary, such as from .salesforce.com to .vf.force.com or .lightning.force.com.
Session identifiers from different contexts, and the sessions themselves, are different. When you transition between contexts, the old session is replaced by the new one, and the old session is no longer valid. The session ID also changes at this time.
Normally Salesforce transparently handles session hand-off between contexts, but if you’re passing the session ID around yourself, you might need to re-access `$Api.Session_ID` or `GETSESSIONID()` from the new context to ensure a valid session ID.
Not all sessions are created equal. In particular, sessions obtained in a Lightning Experience context have reduced privileges, and don't have API access. You can't use these session IDs to make API calls. `{!$Api.Session_ID}` isn’t generated for guest users.
If you use a JWT-based access token for session authentication, you can’t use `$Api.Session_ID`. To use `$Api.Session_ID`, use an opaque access token instead. Make sure that the “Issue JSON Web Token (JWT)-based access tokens for named users” setting isn’t selected for your external client app or connected app.
## Example
- `{!$Api.Enterprise_Server_URL__xxx}`: The Enterprise WSDL SOAP endpoint where _xxx_ represents the version of the API. For example, `{!$Api.Enterprise_Server_URL_260}` is the expression for the endpoint for version 26.0 of the API.
- `{!$Api.Partner_Server_URL__xxx}`: The Partner WSDL SOAP endpoint where _xxx_ represents the version of the API. `{!$Api.Partner_Server_URL_250}` is the expression for the endpoint for version 25.0 of the API.
- `{!$Api.Session_ID}`: The session ID.
# $Asset
A global merge field to use when referencing images and other assets that are part of the Lightning Design System.
## Usage
In a Visualforce page that uses ``, `$Asset.SLDS` allows you to use the images, icons, and avatars that are part of the Lightning Design System. Use the `URLFOR()` formula function to reference assets using `$Asset` with dot notation.
To use SVG icons, add the required XML namespaces by using `xmlns="http://www.w3.org/2000/svg"` and `xmlns:xlink="http://www.w3.org/1999/xlink"` in the `html` tag.
**note:** If you’re using the Salesforce sidebar, header, or built-in style sheets, you can’t add attributes to the `html`. VG icons are supported only if `showHeader`, `standardStylesheets`, and `sidebar` are set to `false`.
## Example
The following markup references an avatar in the Lightning Design System.
```visualforce
```
The following markup references the Lightning Design System’s SVG account icon.
```visualforce
Account Icon
```
**See Also**
- [Using the Lightning Design System](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/styling/pages-styling-slds.md)
# `$Browser`
The `$Browser` global value provider returns information about the hardware and operating system of the browser accessing the application.
|Attribute|Description|
|---------|-----------|
|`formFactor`|Returns a `FormFactor` enum value based on the type of hardware the browser is running on: `DESKTOP` for a desktop client, or `PHONE` for a phone including a mobile phone with a browser and a smartphone.|
|`isAndroid`|Indicates whether the browser is running on an Android device (`true`) or not (`false`).|
|`isIOS`|Due to changes made by Apple, `isIOS` is deprecated because it no longer distinguishes between iPad and MacOS desktop.|
|`isIPad`|Due to changes made by Apple, `isIPad` is deprecated because it no longer distinguishes between iPad and MacOS desktop.|
|`isIPhone`|Not available in all implementations. Indicates whether the browser is running on an iPhone (`true`) or not (`false`).|
|`isPhone`|Indicates whether the browser is running on a phone including a mobile phone with a browser and a smartphone (`true`), or not (`false`).|
|`isTablet`|Indicates whether the browser is running on a tablet with Android 2.2 or later (`true`) or not (`false`).|
|`isWindowsPhone`|Indicates whether the browser is running on a Windows phone (`true`) or not (`false`). This attribute detects only Windows phones and doesn’t detect tablets or other touch-enabled Windows 8 devices.|
**note:** Due to changes made by Apple, `isTablet` is deprecated for iOS devices because `$Browser` no longer distinguishes between iPad and MacOS desktop.
This example shows usage of the `$Browser` global value provider.
```nolang
{!$Browser.isTablet}
{!$Browser.isPhone}
{!$Browser.isAndroid}
{!$Browser.formFactor}
```
Similarly, you can check browser information in a client-side controller using `$A.get()`.
```javascript
({
checkBrowser: function(component) {
var device = $A.get("$Browser.formFactor");
alert("You are using a " + device);
}
})
```
# $Cache.Org
A global merge field to access an org cache from a Visualforce page. Retrieve cached values from a specified partition’s org cache in the referenced org.
## Usage
Use `{!$Cache.Org}` to reference an existing org cache. An org cache consists of data that’s shared across the org. Use dot notation to specify the namespace, partition name, or properties of a cached value.
## Examples
This output text component retrieves a cached value from the myPartition partition and myNamespace namespace with the key `output`.
```visualforce
```
If the cached value is a data structure that has properties or methods, like an Apex list or a custom class, you can access the properties with`$Cache.Org` by using dot notation. For example, this markup invokes the `List.size()` Apex method if the value of `numbersList` is declared as a `List`.
```visualforce
```
If you’re using `CacheBuilder`, qualify the key name with the class that implements the `CacheBuilder` interface and the literal string `_B_`, in addition to the namespace and partition name. In this example, the class that implements `CacheBuilder` is called `CacheBuilderImpl`.
```visualforce
```
**See Also**
- [Cache.Org Class](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_cache_Org.htm#apex_class_cache_Org.htm)
- [Cache.CacheBuilder Interface](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_interface_cache_CacheBuilder.htm#apex_interface_cache_CacheBuilder)
# $Cache.Session
A global merge field to access an org’s session cache from a Visualforce page. Retrieve cached values from a specified partition’s session cache in the referenced org.
## Usage
Use `{!$Cache.Session}` to reference an existing session cache. A session cache consists of cached data that can be reused from one session to the next. Use dot notation to specify the namespace, partition name, or properties of a cached value.
## Examples
This output text component retrieves a cached value from the myPartition partition and myNamespace namespace with the key `output`.
```visualforce
```
If the cached value is a data structure that has properties or methods, like an Apex list or a custom class, you can access the properties with`$Cache.Session` by using dot notation. For example, this markup invokes the `List.size()` Apex method if the value of `numbersList` is declared as a `List`.
```visualforce
```
If you’re using `CacheBuilder`, qualify the key name with the class that implements the `CacheBuilder` interface and the literal string `_B_`, in addition to the namespace and partition name. In this example, the class that implements `CacheBuilder` is called `CacheBuilderImpl`.
```visualforce
```
**See Also**
- [Cache.Session Class](https://help.salesforce.com/s/articleView?id=platform.cl_about.htm&type=5)
- [Cache.CacheBuilder Interface](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_interface_cache_CacheBuilder.htm#apex_interface_cache_CacheBuilder)
# $Component
A global merge field type to use when referencing a Visualforce component.
## Usage
Each component in a Visualforce page has its own `Id` attribute. When the page is rendered, this attribute is used to generate the Document Object Model (DOM) ID. Use `$Component.Path.to.Id` in JavaScript to reference a specific component on a page, where _Path.to.Id_ is a component hierarchy specifier for the component being referenced.
## Example
The following JavaScript method references a component named `msgpost` in a Visualforce page:
```javascript
function beforeTextSave() {
document.getElementById('{!$Component.msgpost}').value =
myEditor.getEditorHTML();
}
```
The page markup that follows shows the `` component to which `msgpost` refers:
```markup
is great.
```
If your component is nested, you might need to use a more complete component path specifier. For example, if your page looks like this:
```visualforce
Heya!
```
Then you can refer to the component in a function like this:
```javascript
document.getElementById(
"{!$Component.theBlock.theSection.theSectionItem.theText}")
```
**See Also**
- [Using $Component to Reference Components from JavaScript](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/javascript/pages-access.md)
- [Best Practices for Accessing Component IDs](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/best-practices/pages-best-practices-accessing-id.md)
# $ComponentLabel
A global merge field to use when referencing the label of an `inputField` component on a Visualforce page that is associated with a message.
## Usage
Return the label of an `inputField` component that is associated with a message.
## Example
```visualforce
```
# $ContentAsset
The `$ContentAsset` global value provider lets you reference images, style sheets, and JavaScript used as asset files in your Lightning components.
Reference `$ContentAsset` asset files by name instead of using cumbersome file paths or URLs. `$ContentAsset` provides sharing, versioning, and access control for all asset files, as well as options for mobile optimization and resizing of image files. You can use `$ContentAsset` in Lightning components markup and within JavaScript controller and helper code.
## Using `$ContentAsset` in Component Markup
To reference a specific asset file in component markup, use `$ContentAsset.yourNamespace__assetName`. Orgs without a namespace can use `$ContentAsset.assetDeveloperName`. Use this syntax regardless of whether an asset is for authenticated or unauthenticated sessions. To reference a content asset within an archive, add `pathinarchive` as a parameter appended to the basic syntax: `$ContentAsset.yourNamespace__assetName + 'pathinarchive=images/sampleImage.jpg'`.
Here are a few examples.
Aura component referencing an image in an archive asset file:
```html
```
Include CSS style sheets or JavaScript libraries in a component using the `` tag.
Aura component using an asset file to style a `div` element:
Markup
```nolang
```
Aura component displays data from a `testDisplayData` JavaScript asset file:
Markup
```nolang
...
...
```
Controller
```nolang
({
displayData : function(component, event, helper) {
var data = _datamap.getData();
component.set("v.TestData", data);
}
})
```
JavaScript (.js) Asset File with DeveloperName `testDisplayData`
```javascript
window._datamap = (function() {
var data = ["Agree", "Disagree", "Strongly Agree", "Strongly Disagree", "Not Applicable"];
return {
getData: function() {
return data.join(", ");
}
};
}());
```
# $CurrentPage
A global merge field type to use when referencing the current Visualforce page or page request.
## Usage
Use this global variable in a Visualforce page to reference the current page name (`$CurrentPage.Name`) or the URL of the current page (`$CurrentPage.URL)`. Use `$CurrentPage.parameters.parameterName` to reference page-request parameters and values, where _parameterName_ is the request parameter being referenced. _parameterName_ isn't case-sensitive.
## Example
```markup
You belong to the {!account.name} account.
You're also a nice person.
```
**See Also**
- [Getting Query String Parameters](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/quick-start/pages-quick-start-query-params-getting.md)
# $FieldSet
Provides access to a field set defined in your organization.
## Usage
Use this in your Visualforce pages to dynamically iterate over fields in a field set. You must prefix this global variable with a reference to the standard or custom object that has the field set.
## Example
```visualforce
```
# $Label
A global merge field type to use when referencing a custom label.
## Usage
Use this expression in a Visualforce page to access a custom label. The returned value depends on the language setting of the contextual user. The value returned is one of the following, in order of precedence:
## Example
```visualforce
```
**See Also**
- [*Salesforce Help*: Custom Labels](https://help.salesforce.com/s/articleView?id=platform.cl_about.htm&type=5)
# $Label.Site
A global merge field type used to reference a standard Sites label in a Visualforce page. As with all standard labels, the label’s message displays according to the user’s language and locale. You can’t modify the message of a standard Sites label. To use a custom message, create a custom label, and then reference the label with the `$Label` global variable.
## Usage
Use this expression in a Visualforce page to access a standard Sites label. When the application server constructs the page to be presented to the end-user’s browser, the value returned depends on the language and locale of the user.
## Example
```visualforce
```
# $Locale
The `$Locale` global value provider returns information about the current user’s preferred locale.
|Attribute|Description|Sample Value|
|---------|-----------|------------|
|`country`|The ISO 3166 representation of the country code based on the language locale.|"US", "DE", "GB"|
|`currency`|The currency symbol.|"$"|
|`currencyCode`|The ISO 4217 representation of the currency code.|"USD"|
|`decimal`|The decimal separator.|"."|
|`firstDayOfWeek`|The first day of the week, where 1 is Sunday.|1|
|`grouping`|The grouping separator.|","|
|`isEasternNameStyle`|Specifies if a name is based on eastern style, for example, `last name first name [middle] [suffix]`.|false|
|`labelForToday`|The label for the Today link on the date picker.|“Today”|
|`language`|The language code based on the language locale.|"en", "de", "zh"|
|`langLocale`|The locale ID.|“en_US”, “en_GB”|
|`nameOfMonths`|The full and short names of the calendar months|{ fullName: “January”, shortName: “Jan” }|
|`nameOfWeekdays`|The full and short names of the calendar weeks|{ fullName: “Sunday”, shortName: “SUN” }|
|`timezone`|The time zone ID.|"America/Los_Angeles"|
|`userLocaleCountry`|The country based on the current user’s locale|“US”|
|`userLocaleLang`|The language based on the current user’s locale|“en”|
|`variant`|Deprecated. The variation for a language dialect.| |
## Number and Date Formatting
|Attribute|Description|Sample Value|
|---------|-----------|------------|
|`currencyFormat`|The currency format.|"¤#,##0.00;(¤#,##0.00)" ¤ represents the currency sign, which is replaced by the currency symbol.|
|`dateFormat`|The date format.|"MMM d, yyyy"|
|`datetimeFormat`|The date time format.|"MMM d, yyyy h:mm:ss a"|
|`longDateFormat`|The long date format.|"MMMM d, yyyy"|
|`numberFormat`|The number format.|"#,##0.###" # represents a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator. Zero (0) replaces # to represent trailing zeros.|
|`percentFormat`|The percentage format.|"#,##0%"|
|`shortDateFormat`|The short date format.|"M/d/yyyy"|
|`shortDatetimeFormat`|The short date time format.|"M/d/yyyy h:mm a"|
|`shortTimeFormat`|The short time format.|"h:mm a"|
|`showJapaneseCalendar`|Specifies whether to show dates in the Japanese Imperial calendar format|false|
|`timeFormat`|The time format.|"h:mm:ss a"|
|`zero`|The character for the zero digit.|“0”|
## Example
This example shows how to retrieve different `$Locale` attributes.
**Component source**
```nolang
{!$Locale.language}
{!$Locale.timezone}
{!$Locale.numberFormat}
{!$Locale.currencyFormat}
```
Similarly, you can check locale information in JavaScript using `$A.get()`.
```javascript
({
checkDevice: function(component) {
var locale = $A.get("$Locale.language");
alert("You are using " + locale);
}
})
```
**See Also**
- [Localization](https://developer.salesforce.com/docs/platform/aura-platform/components/components-l10n.md)
# $MessageChannel
A global merge field type to provide access to a message channel defined in your organization.
## Usage
Use this expression in your Visualforce page to access a message channel and use the Lightning Message Service APIs.
## Examples
```visualforce
Publish SampleMessageChannel
```
# $Network
A global merge field type to use when referencing Experience Cloud site details in a Visualforce email template.
## Usage
Use dot notation to access your Experience Cloud site’s name and login page URL.The login page URL depends on whether the site uses the standard or a custom login page.
**note:** The `$Network` global merge field type works only in the context of Visualforce emails for Experience Cloud sites.
For more flexibility, you can create custom Experience Cloud site email templates in Visualforce. For a Visualforce email template, use the `$Network` global merge field type and its properties, as described in this table. These fields are populated only in Visualforce Experience Cloud site email templates.
|Field Name|Description|
|----------|-----------|
|`$Network.ActionForVerificationEmail`|Used in one-time password (OTP) and device activation emails to specify the action that prompted sending a verification email.|
|`$Network.AsyncVerificationLink`|Used in asynchronous emails to send a verification link (URL) to users. Users click the link to verify their email address with Salesforce. After verifying their email address, external users can log in with a one-time password (OTP) via email (passwordless login).|
|`$Network.BrowserForVerificationEmail`|Used in OTP and device activation emails to specify the browser where the action occurred that prompted sending a verification email.|
|`$Network.CodeForVerificationEmail`|The verification code sent in the OTP or device activation email.|
|`$Network.ChgEmailVerOldEmail`|The user’s old email address, when they change it.|
|`$Network.ChgEmailVerNewEmail`|The user’s new email address, when they change it.|
|`$Network.ChgEmailVerLink`|The link, sent to the user’s new email address, that the user follows to verify their email address change.|
|`$Network.Name`|The name of the Experience Cloud site.|
|`$Network.NetworkUrlForUserEmails`|The URL to the login page of the Experience Cloud site, for example, https://_MyDomainName_.my.site.com/partners/login.If this merge field is in the welcome email to new members, the URL is appended with a link to a reset password page.|
|`$Network.OperatingSystemForVerificationEmail`|Used in OTP and device activation emails to specify the operating system where the action occurred that prompted sending a verification email.|
|`$Network.passwordLockTime` or `{!PASSWORD_LOCK_TIME}`|Used in the formula field for lockout emails to specify how long a user must wait until logging in again after being locked out.|
## Example
```visualforce
{!$Network.Name}
{!$Network.NetworkUrlForUserEmails}
```
# $ObjectType
A global merge field type to use when referencing standard or custom objects (such as Accounts, Cases, or Opportunities) and the values of their fields.
## Usage
Use dot notation to specify an object, such as `{!$ObjectType.Case}`.
Optionally, select a field on that object using the following syntax: `{!$ObjectType.Role_Limit__c.Fields.Limit__c}`.
## Example
This example retrieves the label for the Account `Name` field:
```visualforce
{!$ObjectType.Account.Fields.Name.Label}
```
You can also use dynamic references to retrieve information about an object through `$ObjectType`. For example, `{!$ObjectType.Account.Fields['Name'].Type}`
- **[Object Schema Details Available Using $ObjectType](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-variables-global-objecttype-schema-objects-reference.md)**
Use the `$ObjectType` global variable to access schema information about the objects in your organization. For example, to access the name, label, and accessibility of an object.
- **[Field Schema Details Available Using $ObjectType](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-variables-global-objecttype-schema-fields-reference.md)**
The `$ObjectType` global variable provides access to a variety of schema information about the objects in your organization. Use it to reference names, labels, and data types of fields on an object, for example.
**See Also**
- [Dynamic References to Schema Details Using $ObjectType](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/dynamic-vf/pages-dynamic-vf-globals-objecttype.md)
# $Organization
A global merge field type to use when referencing information about your company profile. Use organization merge fields to reference your organization’s city, fax, ID, or other details.
## Usage
Use dot notation to access your organization’s information. For example:
```visualforce
{!$Organization.Street}
{!$Organization.State}
```
The organization merge fields get their values from whatever values are currently stored as part of your company information in Salesforce.
Note that `{!$Organization.UiSkin}` is a picklist value, and so should be used with picklist functions such as `ISPICKVAL()` in custom fields, validation rules, Visualforce expressions, flow formulas, process formulas, and workflow rule formulas.
## Example
Values accessible using the `$Organization` global variable include:
```visualforce
{!$Organization.Id}
{!$Organization.Name}
{!$Organization.Division}
{!$Organization.Street}
{!$Organization.City}
{!$Organization.State}
{!$Organization.PostalCode}
{!$Organization.Country}
{!$Organization.Fax}
{!$Organization.Phone}
{!$Organization.GoogleAppsDomain}
{!$Organization.UiSkin}
```
# $Page
A global merge field type to use when referencing a Visualforce page.
## Usage
Use this expression in a Visualforce page to link to another Visualforce page.
## Example
```visualforce
Linked
This is a link to another page.
```
# \$Permission
A global merge field type to use when referencing information about the current user’s custom permission access. Use permission merge fields to reference information about the user’s current access to any of your organization’s custom permissions.
## Usage
1. Select the field type: \$Permission.
2. Select a merge field such as `$Permission.customPermissionName`.
## Example
To have a pageblock only appear for users that have the custom permission seeExecutiveData, use the following.
```visualforce
```
**note:** \$Permission appears only if custom permissions have been created in your organization. For more information, see [Custom Permissions](https://help.salesforce.com/s/articleView?id=platform.custom_perms_overview.htm&type=5).
# $Profile
A global merge field type to use when referencing information about the current user’s profile. Use profile merge fields to reference information about the user’s profile such as license type or name.
## Usage
Use dot notation to access your organization’s information.
Note that you can’t use the following `$Profile` values in Visualforce:
- `LicenseType`
- `UserType`
## Example
```visualforce
{!$Profile.Id}
{!$Profile.Name}
```
# $Resource
The `$Resource` global value provider lets you reference images, style sheets, and JavaScript code you’ve uploaded in static resources.
Using `$Resource` lets you reference assets by name, without worrying about the gory details of URLs or file paths. You can use `$Resource` in Aura component markup and within JavaScript controller and helper code.
## Using `$Resource` in Component Markup
To reference a specific resource in component markup, use `$Resource.resourceName` within an expression. _resourceName_ is the `Name` of the static resource. In a managed package, the resource name must include the package namespace prefix, such as `$Resource.yourNamespace__resourceName`. For a stand-alone static resource, such as an individual graphic or script, you only need the name of the resource. For example, if you uploaded `myScript.js` and set the `Name` to `myScript`, reference it as `$Resource.myScript`. To reference an item within an archive static resource, add the rest of the path to the item using string concatenation. Here are a few examples.
```html
```
Include CSS style sheets or JavaScript libraries into a component using the `` tag. For example:
```nolang
```
**note:** Due to a quirk in the way `$Resource` is parsed in expressions, use the `join` operator to include multiple `$Resource` references in a single attribute. For example, if you have more than one JavaScript library to include into a component the `scripts` attribute should be something like the following.
```nolang
scripts="{!join(',',
$Resource.jsLibraries + '/jsLibOne.js',
$Resource.jsLibraries + '/jsLibTwo.js')}"
```
## Using `$Resource` in JavaScript
To obtain a reference to a static resource in JavaScript code, use `$A.get('$Resource.resourceName')`.
_resourceName_ is the `Name` of the static resource. In a managed package, the resource name must include the package namespace prefix, such as $Resource.yourNamespace__resourceName. For a stand-alone static resource, such as an individual graphic or script, you only need the name of the resource. For example, if you uploaded `myScript.js` and set the `Name` to `myScript`, reference it as `$Resource.myScript`. To reference an item within an archive static resource, add the rest of the path to the item using string concatenation. For example:
```javascript
({
profileUrl: function(component) {
var profUrl = $A.get('$Resource.yourGraphics') + '/images/avatar1.jpg';
alert("Profile URL: " + profUrl);
}
})
```
**note:** Static resources referenced in JavaScript aren’t automatically added to packages. If your JavaScript depends on a resource that isn’t referenced in component markup, add it manually to any packages the JavaScript code is included in.
## `$Resource` Considerations
Global value providers in the Aura Components programming model are, behind the scenes, implemented quite differently from global variables in Salesforce. Although `$Resource` looks like the global variable with the same name available in Visualforce, formula fields, and elsewhere, there are important differences. Don’t use other documentation as a guideline for its use or behavior.
Here are two specific things to keep in mind about `$Resource` in the Aura Components programming model.
First, `$Resource` isn’t available until the Aura Components programming model is loaded on the client. Some very simple components that are composed of only markup can be rendered server-side, where `$Resource` isn’t available. To avoid this, when you create a new app, stub out a client-side controller to force components to be rendered on the client.
Second, if you’ve worked with the `$Resource` global variable, in Visualforce or elsewhere, you’ve also used the `URLFOR()` formula function to construct complete URLs to specific resources. There’s nothing similar to `URLFOR()` in the Aura Components programming model. Instead, use simple string concatenation, as illustrated in the preceding examples.
**See Also**
- [*Salesforce Help*: Static Resources](https://help.salesforce.com/apex/HTViewHelpDoc?id=pages_static_resources.htm)
# $Resource
A global merge field type to use when referencing an existing static resource by name in a Visualforce page. You can also use resource merge fields in `URLFOR` functions to reference a particular file in a static resource archive.
## Usage
Use `{!$Resource}` to reference an existing static resource. The format is `{!$Resource.nameOfResource}`, such as `{!$Resource.TestImage}`.
## Examples
The Visualforce component below references an image file that was uploaded as a static resource and given the name `TestImage`:
```visualforce
```
To reference a file in an archive (such as a .zip or .jar file), use the `URLFOR` function. Specify the static resource name that you provided when you uploaded the archive with the first parameter, and the path to the desired file within the archive with the second. For example:
```visualforce
```
You can also use dynamic references to reference static resources. For example, `{!$Resource[appLogo]}`, assuming there is an `appLogo` property or `getAppLogo()` method in your page’s controller.
**See Also**
- [Styling Visualforce Pages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/styling/pages-styling.md)
# $SControl
A global merge field type to use when referencing an existing custom s-control by name. This merge field type results in a URL to a page where the s-control executes.
**important:** Visualforce pages supersede s-controls. Organizations that haven't previously used s-controls can’t create them. Existing s-controls are unaffected and can still be edited.
## Usage
Use dot notation to access an existing s-control by its name.
## Example
The following example shows how to link to an s-control named HelloWorld in a Visualforce page:
```markup
Open the HelloWorld s-control
```
Note that if you simply want to embed an s-control in a page, you can use the `` tag without the $SControl merge field. For example:
```markup
```
# $Setup
A global merge field type to use when referencing a custom setting of type “hierarchy.”
## Usage
Use `$Setup` to access hierarchical custom settings and their field values using dot notation. For example, `$Setup.App_Prefs__c.Show_Help_Content__c`.
Hierarchical custom settings allow values at any of three different levels:
1. Organization, the default value for everyone
2. Profile, which overrides the Organization value
3. User, which overrides both Organization and Profile values
Salesforce automatically determines the correct value for this custom setting field based on the running user’s current context.
Custom settings of type “list” aren’t available on Visualforce pages using this global variable. You can access list custom settings in Apex.
## Example
The following example illustrates how to conditionally display an extended help message for an input field, depending on the user’s preference:
```visualforce
Enter the height for your workstation in inches, measured from the
floor to top of the work surface.
...
```
If the organization level for the custom setting is set to `true`, users see the extended help message by default. If an individual prefers to not see the help messages, they can set their custom setting to `false`, to override the organization (or profile) value.
# $Site
A global merge field type to use when referencing information about the current Salesforce site.
## Usage
Use dot notation to access information about the current Salesforce site. Note that only the following site fields are available:
|Merge Field|Description|
|-----------|-----------|
|$Site.Name|Returns the API name of the current site.|
|$Site.Domain|Returns your Salesforce Sites based URL.|
|$Site.CustomWebAddress|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 an empty string. 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 field returns an empty string. This field's value always ends with a `/` character. Use of $Site.CustomWebAddress is discouraged and we recommend using $Site.BaseCustomUrl instead.|
|$Site.OriginalUrl|Returns the original URL for this page if it’s a designated error page for the site; otherwise, returns `null`.|
|$Site.CurrentSiteUrl|Returns the base URL of the current site that references and links should use. Note that this field might return the referring page's URL instead of the current request's URL. This field's value includes a path prefix and always ends with a `/` character. If the current request is not a site request, then this field returns an empty string. Use of $Site.CurrentSiteUrl is discouraged. Use $Site.BaseUrl instead.|
|$Site.LoginEnabled|Returns `true` if the current site is associated with an active login-enabled portal; otherwise returns `false`.|
|$Site.RegistrationEnabled|Returns `true` if the current site is associated with an active self-registration-enabled Customer Portal; otherwise returns `false`.|
|$Site.IsPasswordExpired|For authenticated users, returns `true` if the currently logged-in user's password is expired. For non-authenticated users, returns `false`.|
|$Site.AdminEmailAddress|Returns an empty string. This merge field is deprecated.|
|$Site.Prefix|Returns the URL path prefix of the current site. For example, if your site URL is _MyDomainName_.my.salesforce-sites.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 field returns an empty string.|
|$Site.Template|Returns the template name associated with the current site; returns the default template if no template has been designated.|
|$Site.ErrorMessage|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.|
|$Site.ErrorDescription|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.|
|$Site.AnalyticsTrackingCode|The tracking code associated with your site. Services such as Google Analytics can use this code to track page request data for your site.|
|$Site.BaseCustomUrl|Returns a base URL for the current site that doesn’t use a 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 salesforce-sites.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 field replaces `CustomWebAddress` and includes the custom URL's path prefix.|
|$Site.BaseInsecureUrl|This merge field is deprecated. 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|
|$Site.BaseRequestUrl|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.|
|$Site.BaseSecureUrl|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 there are no HTTPS custom URLs 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.|
|$Site.BaseUrl|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. This field's 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 $Site.CurrentSiteUrl.|
|$Site.MasterLabel|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 an empty string.|
|$Site.SiteId|Returns the ID of the current site. If the current request is not a site request, then this field returns an empty string.|
|$Site.SiteType|Returns the API value of the Site Type field for the current site. If the current request is not a site request, then this field returns an empty string.|
|$Site.SiteTypeLabel|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 field returns an empty string.|
## Example
The following example shows how to use the `$Site.Template` merge field:
```visualforce
```
# $System.OriginDateTime
A global merge field that represents the literal value of 1900-01-01 00:00:00.
## Usage
Use this global variable when performing date/time offset calculations, or to assign a literal value to a date/time field.
## Example
The following example calculates the number of days that have passed since January 1, 1900:
```nolang
{!NOW() - $System.OriginDateTime}
```
# $User
A global merge field type to use when referencing information about the current user. User merge fields can reference information about the user such as alias, title, and ID.
Most of the fields available on the [User standard object](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) are also available on $User.
## Usage
Use dot notation to access the current user’s information. For example:
```visualforce
{!IF (CONTAINS($User.Alias, Smith) True, False)}
```
## Example
The following example displays the current user’s company name, as well as the status of the current user (which returns a Boolean value).
```visualforce
Congratulations
This is your new Apex Page
The current company name for this
user is: {!$User.CompanyName}
Is the user active?
{!$User.isActive}
```
# $User.UITheme and $User.UIThemeDisplayed
These global merge fields identify the Salesforce look and feel a user sees on a given Web page.
The difference between the two variables is that `$User.UITheme` returns the look and feel the user is supposed to see, while `$User.UIThemeDisplayed` returns the look and feel the user actually sees. For example, a user can have the preference and permissions to see the Lightning Experience look and feel, but if they’re using a browser that doesn’t support that look and feel, for example, older versions of Internet Explorer, `$User.UIThemeDisplayed` returns a different value.
## Usage
Use these variables to identify the CSS used to render Salesforce web pages to a user. Both variables return one of the following values.
Valid values include:
- `Theme1`—Obsolete Salesforce theme
- `Theme2`—Salesforce Classic 2005 user interface theme
- `Theme3`—Salesforce Classic 2010 user interface theme
- `Theme4d`—Modern “Lightning Experience” Salesforce theme
- `Theme4t`—Salesforce mobile app theme
- `Theme4u`—Lightning Console theme
- `PortalDefault`—Salesforce Customer Portal theme that applies to Customer Portals only and not to Experience Builder sites
- `Webstore`—AppExchange theme
## Example
The following example shows how you can render different layouts based on a user’s theme:
```visualforce
// this is the old theme...
// this is the classic theme ...
```
# $UserRole
A global merge field type to use when referencing information about the current user’s role. Role merge fields can reference information such as role name, description, and ID.
## Usage
Use dot notation to access information about the current user’s role.
Note that you can’t use the following `$UserRole` values in Visualforce:
- `CaseAccessForAccountOwner`
- `ContactAccessForAccountOwner`
- `OpportunityAccessForAccountOwner`
- `PortalType`
## Example
```visualforce
{!$UserRole.LastModifiedById}
```
# A Simple Charting Example
A Visualforce chart requires that you create a chart container component, which encloses at least one data series component. You can optionally add additional series components, chart axes, as well as labeling components such as a legend, chart labels, and tooltips for data points.
Here is a simple pie chart and the markup that creates it:

```apex_page
```
The `` component defines the chart container, and binds the component to the data source, the `getPieData()` controller method. The `` describes the label and data fields to access in the returned data, to label and size each data point.
Here’s the associated controller:
```apex_code
public class PieChartController {
public List getPieData() {
List data = new List();
data.add(new PieWedgeData('Jan', 30));
data.add(new PieWedgeData('Feb', 15));
data.add(new PieWedgeData('Mar', 10));
data.add(new PieWedgeData('Apr', 20));
data.add(new PieWedgeData('May', 20));
data.add(new PieWedgeData('Jun', 5));
return data;
}
// Wrapper class
public class PieWedgeData {
public String name { get; set; }
public Integer data { get; set; }
public PieWedgeData(String name, Integer data) {
this.name = name;
this.data = data;
}
}
}
```
This controller is deliberately simple; you normally issue one or more SOQL queries to collect your data.
These are the important points illustrated by the example:
- The `getPieData()` method returns a List of simple objects, an inner class PieWedgeData used as a wrapper. Each element in the list is used to create a data point.
- The PieWedgeData class is just a set of properties, and is essentially used as a `name`=_value_ store.
- The chart series component `` defines which properties from the PieWedgeData class to use to determine each point in the series. In this simple example there’s no mystery, but in charts with multiple series and axes this convention allows the efficient return of the entire data set in one List object.
# A Simple Example of Remote Objects
This short example demonstrates the two pieces of functionality you need to implement to use Remote Objects.
This Visualforce page retrieves a list of 10 Warehouse records and displays them on the page in response to the user clicking the **Retrieve Warehouses** button.
```markup
Retrieve Warehouses via Remote Objects
Warehouses:
```
Notice something unusual about this page—there is no controller or controller extension. All of the data access is handled by the Remote Objects components.
The first part of this example is the Remote Objects components that specify which objects and fields to make accessible on the page.
```visualforce
```
These components generate JavaScript model classes, one per sObject in the access specification, which you use to make data access calls directly from your JavaScript code. Notice the use of the `jsShorthand` attribute, which maps the full Salesforce API name to a simpler, shorter name to use in your JavaScript code. If you plan to package and distribute your code, setting `jsShorthand` is essential because it eliminates the use of your organization’s namespace in the packaged code. Using the shorthand does all the work.
The second part of this example is a JavaScript function that uses the models that are generated by the access definition components to retrieve a set of records for display on the page.
```javascript
```
The first line of the function creates a Warehouse object from the model. Notice that the call that creates it uses the `jsShorthand` for the sObject instead of the full API name of the object. Following this best practice decouples your JavaScript code from the specifics of your organization namespace, sObject and field names, and so on, and makes your code more succinct and clear.
The second line uses the new Warehouse object, `wh`, to perform a query for Warehouse records. The call provides two arguments: a simple query specifier and an anonymous function to handle the results. The function is standard JavaScript. It iterates over the results and creates list items to append to the list of warehouses on the page.
The page body is static HTML.
```visualforce
Retrieve Warehouses via Remote Objects
Warehouses:
```
Your code adds results to the `warehousesList` list. When the page loads, the list is empty. Clicking the button fires the JavaScript function that was defined earlier, which performs the query and adds the results.
# Abort a Job
If you abort a job, Salesforce doesn’t process the job.
**URI:** `/services/data/vXX.X/jobs/ingest/jobID`
**Availability:** This resource is available in API version 41.0 and later.
**Formats:** JSON
**HTTP Method:** PATCH
**Authentication:** `Authorization: Bearer token`
**Parameters:** None.
**Request Body**
| Property | Type | Description | Required or Optional |
| -------- | ------------ | ------------------------------------------------------------- | -------------------- |
| `state` | JobStateEnum | The state to update the job to. Use `Aborted` to abort a job. | Required |
**Response Body**
| Property | Type | Description |
| --------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiVersion` | string | The API version that the job was created in. |
| `assignmentRuleId` | id | The ID of the assignment rule. This property is only shown if an assignment rule is specified when the job is created. |
| `columnDelimiter` | ColumnDelimiterEnum | The column delimiter used for CSV job data. Values include:
`BACKQUOTE`—backquote character (\`)
`CARET`—caret character (^)
`COMMA`—comma character (,) which is the default delimiter
`PIPE`—pipe character (\|)
`SEMICOLON`—semicolon character (;)
`TAB`—tab character
|
| `concurrencyMode` | ConcurrencyModeEnum | For future use. How the request was processed. Currently only parallel mode is supported. (When other modes are added, the mode will be chosen automatically by the API and will not be user configurable.) |
| `contentType` | ContentType | The format of the data being processed. Only CSV is supported. |
| `contentUrl` | URL | The URL to use for [Upload Job Data](https://developer.salesforce.com/docs/platform/api-asynch/guide/upload-job-data.md#upload-job-data) requests for this job. Only valid if the job is in `Open` state. |
| `createdById` | string | The ID of the user who created the job. |
| `createdDate` | dateTime | The date and time in the UTC time zone when the job was created. |
| `externalIdFieldName` | string | The name of the external ID field for an upsert. |
| `id` | string | Unique ID for this job. |
| `jobType` | JobTypeEnum | The job’s type. Values include:
`BigObjectIngest`—BigObjects job
`Classic`—Bulk API 1.0 job
`V2Ingest`—Bulk API 2.0 job
|
| `lineEnding` | LineEndingEnum | The line ending used for CSV job data. Values include:
`LF`—linefeed character
`CRLF`—carriage return character followed by a linefeed character
|
| `object` | string | The object type for the data being processed. Empty for jobs created with the `consentImport` operation. |
| `operation` | | The processing operation for the job. Values include:
`insert`
`delete`
`hardDelete`
`update`
`upsert`
`refresh`
`consentImport`
|
| `state` | JobStateEnum | The current state of processing for the job. Values include:
`Open`—The job has been created, and data can be added to the job.
`UploadComplete`—No new data can be added to this job. You can’t edit or save this job, as Salesforce is processing it.
`Aborted`—The job has been aborted. You can abort a job if you created it or if you have the “Manage Data Integrations” permission.
`JobComplete`—The job was processed by Salesforce.
`Failed`—Some records in the job failed. Job data that was successfully processed isn’t rolled back.
|
| `systemModstamp` | dateTime | Date and time in the UTC time zone when the job finished. |
# Abort a Query Job
Aborts a query job.
**note:** - To abort a job, you must be the job’s creator or have the Manage Data Integrations permission.
- You can only abort jobs that are in the following states:
- `UploadComplete`
- `InProgress`
## Syntax
**URI:** `/services/data/vXX.X/jobs/query/queryJobId`
**Available since release:**
This resource is available in API version 47.0 and later.
**Formats:** JSON
**HTTP methods:** PATCH
**Authentication:** Authorization: Bearer token
**Request body**
The request body must be the following:
```nolang
{
"state": "Aborted"
}
```
**Request parameters:**
| Parameter | Description | Required or Optional |
| ------------ | -------------------------------------- | -------------------- |
| `queryJobId` | The ID of the query job to be deleted. | Required |
**Response Body**
If the request is successful, the status code is 200 (OK). The response body has the state `Aborted`. For example:
```nolang
{
"id" : "750R000000146UvIAI",
"operation" : "query",
"object" : "Account",
"createdById" : "005R0000000GiwjIAC",
"createdDate" : "2018-12-18T16:15:31.000+0000",
"systemModstamp" : "2018-12-18T16:15:32.000+0000",
"state" : "Aborted",
"concurrencyMode" : "Parallel",
"contentType" : "CSV",
"apiVersion" : 46.0
}
```
**Response Parameters:**
| Parameter | Description |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id` | The unique ID for this job. |
| `operation` | The type of query. Possible values are:
`query`—Returns data that hasn’t been deleted or archived. For more information, see [query()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_query.htm) in _SOAP API Developer Guide_.
`queryAll`—Returns records that have been deleted because of a merge or delete, and returns information about archived Task and Event records. For more information, see [queryAll()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_queryall.htm) in _SOAP API Developer Guide_.
|
| `object` | The object type being queried. |
| `createdById` | The ID of the user who created the job. |
| `createdDate` | The UTC date and time when the job was created. |
| `systemModstamp` | The UTC date and time when the API last updated the job information. |
| `state` | The current state of processing for the job. Possible values are:
`UploadComplete`—The job is ready to be processed and Salesforce has put the job in the queue.
`InProgress`—Salesforce is processing the job.
`Aborted`—The job has been aborted. See [Abort a Query Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/query-abort-job.md).
`JobComplete`—Salesforce has finished processing the job.
`Failed`—The job failed.
|
| `concurrencyMode` | Reserved for future use. How the request is processed. Currently only parallel mode is supported. (When other modes are added, the API chooses the mode automatically. The mode isn’t user configurable.) |
| `contentType` | The format that is used for the results. Currently the only supported value is `CSV`. |
| `apiVersion` | The API version that the job was created in. |
**Response Body - For an Unsuccessful Request**
If the request fails, the server returns a non-200 status, and the request body shows details of the error. For example:
```nolang
HTTP/1.1 400 Bad Request
[{
"errorCode": "INVALIDJOBSTATE",
"message": "Aborting already Completed Job not allowed"
}]
```
## Example
This example aborts the job with ID `750R000000146UvIAI`:
```nolang
curl --request PATCH \
--header "Authorization: Bearer token" \
--header "Content-Type: application/json" \
--data '{
"state": "Aborted"
}' \
https://instance.salesforce.com/services/data/vXX.X/jobs/query/750R000000146UvIAI
```
The response is:
```nolang
{
"id": "750R000000146UvIAI",
"operation": "query",
"object": "Account",
"createdById": "005R0000000GiwjIAC",
"createdDate": "2018-12-18T20:51:39.000+0000",
"systemModstamp": "2018-12-18T20:51:41.000+0000",
"state": "Aborted",
"concurrencyMode": "Parallel",
"contentType": "CSV",
"apiVersion": 46.0
}
```
# About REST API
REST API is one of several web interfaces that you can use to access your Salesforce data without using the Salesforce user interface. With API access, you can perform operations and integrate Salesforce into your applications as you like.
You can use REST API tools to create, manipulate, and search data in Salesforce by sending HTTP requests to endpoints in Salesforce. Depending on where you send requests, you access and operate on different pieces of information, called resources. Resources include records, query results, metadata, and more.
REST API uses RESTful architecture to provide a straightforward and consistent interface. A primary benefit of REST API is that it doesn’t require much tooling to access your data. It’s simpler to use than SOAP API but still provides plenty of functionality.
Although REST API is great for accessing and querying records, other Salesforce APIs, such as Bulk 2.0 API, Metadata API, and Connect REST API, offer additional functionality for specific tasks.
**See Also**
- [REST Resources and Requests](https://developer.salesforce.com/docs/platform/api-rest/guide/intro-rest-resources.md)
- [REST API Architecture](https://developer.salesforce.com/docs/platform/api-rest/guide/intro-rest-architecture.md)
# About SOAP API
Salesforce provides programmatic access to your org’s information using simple, powerful, and secure application programming interfaces. Before reading more about SOAP API, you should have a basic familiarity with software development, web services, and the Salesforce user interface.
Any functionality described in this guide is available if your org has the API feature enabled. This feature is enabled by default for Performance, Unlimited, Enterprise, and Developer Editions. Some Professional Edition orgs have the API enabled. If you can’t access the features you see in this guide, contact Salesforce.
Salesforce offers several APIs in addition to SOAP API. If you’re wondering whether SOAP API is the right tool to use, check out [Which API Do I Use?](https://help.salesforce.com/s/articleView?id=platform.integrate_what_is_api.htm&type=5) in *Salesforce Help*.
**tip:** Salesforce SOAP API is designed to work with Salesforce objects. See the [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_concepts.htm) for an introduction and more information about Salesforce objects.
## Customize, Integrate, and Extend Your Salesforce Solutions
The Lightning Platform allows you to customize, integrate, and extend your Salesforce organization using the language and platform of your choice:
- **Customize Salesforce** with custom fields, links, objects, page layouts, buttons, record types, s-controls, and tabs to meet specific business requirements.
- **Integrate Salesforce** with your org’s ERP and finance systems. Deliver real-time sales and support information to company portals and populate critical business systems with customer information.
- **Extend Salesforce** in presentation, business logic, and data services with new functionality that reflects the business requirements of your org.
For more information about Lightning Platform solutions and developer resources, go to [Salesforce Developers](https://developer.salesforce.com/).
## Supported Editions and Required Permissions
To use SOAP API, your org must use Enterprise Edition, Performance Edition, Unlimited Edition, or Developer Edition. If you’re an existing Salesforce customer and want to upgrade to Enterprise, Unlimited, or Performance Edition, contact your account representative.
To protect the configuration and live data in your production org, we recommend building and testing all solutions and changes in an isolated environment, such as a Developer Edition, sandbox, or scratch org.
Developer Edition provides access to all features available with Enterprise Edition, but is constrained by the number of users and the amount of storage space in each org. Sign up for a free [Developer Edition](https://developer.salesforce.com/signup). Sandboxes create copies of your existing org into separate environments. For more information, see [Sandboxes: Staging Environments for Customizing and Testing](https://help.salesforce.com/articleView?id=deploy_sandboxes_parent.htm). A scratch org is a source-driven and disposable deployment that’s fully configurable, allowing you to emulate different Salesforce editions with different features and preferences. For more information, see [Scratch Orgs](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_scratch_orgs.htm)
In all supported editions, a user must have the API Enabled permission turned on in the user profile they’re assigned. This permission is enabled by default on some profiles, including many profiles available in Developer Edition orgs. In supported editions, you can also use the Salesforce Integration user license to grant system-to-system integration users org access while limiting them to API-only operations. For more information, see Salesforce Help: [Give Integration Users API Only Access](https://help.salesforce.com/s/articleView?id=platform.integration_user.htm&type=5).
## Standards Compliance
SOAP API is implemented to comply with the following specifications:
|Standard Name|Website|
|-------------|-------|
|Simple Object Access Protocol (SOAP) 1.1|[https://www.w3.org/TR/2000/NOTE-SOAP-20000508/](https://www.w3.org/TR/2000/NOTE-SOAP-20000508/)|
|Web Service Description Language (WSDL) 1.1|[http://www.w3.org/TR/2001/NOTE-wsdl-20010315](http://www.w3.org/TR/2001/NOTE-wsdl-20010315)|
|WS-I Basic Profile 1.1|[http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html](http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html)|
## Development Platforms
SOAP API works with current SOAP development environments, including, but not limited to, Visual Studio .NET 2005. In this document, we provide examples in Java and C# (.NET). The Java examples are based on WSC 20.0 (WSC) and JDK 6 (Java Platform Standard Edition Development Kit 6). Other versions of WSC are available at [https://github.com/forcedotcom/wsc](https://github.com/forcedotcom/wsc) and [https://mvnrepository.com/artifact/com.force.api/force-wsc](https://mvnrepository.com/artifact/com.force.api/force-wsc). To see a complete list of compatible development platforms and more sample code, go to [developer.salesforce.com](https://developer.salesforce.com/).
**note:** Development platforms vary in their SOAP implementations. Implementation differences in certain development platforms might prevent access to some or all features of the API. If you’re using Visual Studio for .NET development, we recommend that you use Visual Studio 2003 or higher.
## SOAP API Support Policy
Salesforce recommends that your new client applications use the most recent version of the Lightning Platform WSDL file to fully exploit the benefits of richer features and greater efficiency. You can navigate to the most recent WSDL for your organization from Setup by entering `API` in the Quick Find box, then selecting **API**. When a new version is released, use the following steps in [Quick Start](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps.md) to update your WSDL:
- Regenerate the WSDL file (see [Step 2: Generate or Obtain the Web Service WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-generate-wsdl.md))
- Import it into your environment (see [Step 3: Import the WSDL File Into Your Development Platform](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-import-wsdl.md))
### Compatibility
Each new Salesforce release consists of two components:
- A new release of platform software that resides on Salesforce systems
- A new version of SOAP API
For example, the Winter ’24 release included SOAP API version 59.0 and the Spring ’24 release included SOAP API version 60.0. For more information about API versions, see [Find Salesforce Edition and API version](https://help.salesforce.com/s/articleView?id=000386929&type=1&language=en_US).
Salesforce does not guarantee that an application written against one SOAP API version will work with future SOAP API versions: Changes in method signatures and data representations are often required as we continue to enhance SOAP API. However, we strive to keep SOAP API consistent from version to version with minimal, if any, changes required to port applications to newer SOAP API versions.
For information about Salesforce Platform API versions that are deprecated or retired, see [Salesforce Platform API Versions 21.0 through 30.0 Retirement ](https://help.salesforce.com/s/articleView?id=000389618&type=1&language=en_US).
## Choosing a WSDL
There are two Lightning Platform Web services for which you can obtain WSDL files for API access:
- **Lightning Platform Enterprise WSDL**—This API is for most enterprise users who are developing client applications for their org. The enterprise WSDL file is a strongly typed representation of your org’s data. It provides information about your schema, data types, and fields to your development environment, allowing for a tighter integration between it and the Lightning Platform Web service. This WSDL changes if custom fields or custom objects are added to, renamed, or removed from, your org’s Salesforce configuration. If you are downloading an enterprise WSDL and you have managed packages installed in your organization, you need to take an extra step to select the version of each installed package to include in the generated WSDL.
Note the following when generating the enterprise WSDL:
- If new custom fields or objects are added to, renamed, or removed from your org’s information, you must regenerate the WSDL file to access them.
- The generated WSDL contains the objects and fields in your org, including those available in the selected versions of each installed package. If a field or object is added in a later package version, you must generate the enterprise WSDL with that package version to work with the object or field in your API integration.
- **Lightning Platform Partner WSDL**—This API is for Salesforce partners who are developing client applications for multiple orgs. As a loosely-typed representation of the Salesforce object model, the partner WSDL can be used to access data within any org.
## Related Resources
The Salesforce developer website provides a full suite of developer toolkits, sample code, sample SOAP messages, community-based support, and other resources to help you with your development projects. Be sure to visit [developer.salesforce.com](https://developer.salesforce.com/gettingstarted) for more information, or visit [developer.salesforce.com/signup](https://developer.salesforce.com/signup) to sign up for a free Developer Edition account.
You can visit these websites to find out more about Salesforce applications:
- [Salesforce](https://salesforce.com) for information about the Salesforce application.
- [Salesforce AppExchange](https://appexchange.salesforce.com/) for access to apps created for Salesforce.
- [Trailblazer Community](https://trailhead.salesforce.com/en/trailblazer-community/feed) for services to ensure Salesforce customer success.
# About the Visualforce Editor
When editing Visualforce pages through the development mode footer or from Setup, an editor is available with the following functionality:
## Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
## Search
The Search button () enables you to search for text within the current page, class, or trigger. To use search, enter a string in the `Search` textbox and click **Find Next**.
- To replace a found search string with another string, enter the new string in the `Replace` textbox and click **replace** to replace just that instance, or **Replace All** to replace that instance and all other instances of the search string that occur in the page, class, or trigger.
- To make the search operation case sensitive, select the **Match Case** option.
- To use a regular expression as your search string, select the **Regular Expressions** option. The regular expressions follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression group variables (`$1`, `$2`, and so on) from the found search string. For example, to replace an `
` tag with an `
` tag and keep all the attributes on the original `
` intact, search for `
` and replace it with `
`.
## Go to line
The Go to line button () allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line.
## Undo and Redo
Use undo () to reverse an editing action and redo () to recreate an editing action that was undone.
## Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
## Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line () to quickly navigate through the editor.
## Line and character count
The total number of lines and characters is displayed in the status bar at the bottom of the editor.
The editor supports the following keyboard shortcuts:
## `Tab`
Adds a tab at the cursor
## `SHIFT+Tab`
Removes a tab
## `CTRL+f`
Opens the search dialog or searches for the next occurrence of the current search
## `CTRL+r`
Opens the search dialog or replaces the next occurrence of the current search with the specified replacement string
## `CTRL+g`
Opens the go to line dialog
## `CTRL+s`
Performs a quick save.
## `CTRL+z`
Reverses the last editing action
## `CTRL+y`
Recreates the last editing action that was undone
# About This Developer Guide
Documentation for LWC Offline is a work in progress, and will improve continuously throughout the pilot and beta programs. The initial release of the program documentation is shared across several LWC Offline-enabled mobile apps. Use this developer guide for the purpose of evaluating LWC Offline in your own orgs.
Where possible, documentation refers to LWC Offline features generally, and applies to all LWC Offline-enabled mobile apps. However, these efforts are in progress and incomplete. You’ll likely notice references to Field Service in the documentation, and some instructions might be specific to Field Service. In the early stages of this pilot, we’ll ask for your forbearance and forgiveness.
In the meantime, if you’re unable to interpret these differences, don’t hesitate to reach out with questions on the relevant Trailblazer community.
# About This Quick Reference
This quick reference provides common limits and allocations for Salesforce and doesn’t cover all limits and allocations. It might contain limits or allocations that don’t apply to your Salesforce org. Stated limits aren’t a promise that the specified resource is available at its limit in all circumstances. Load, performance, and other system issues can prevent some limits from being reached. Limits can change without notice.
This guide doesn’t include limits or allocations for:
- User interface elements in the Salesforce application
- Field lengths of Salesforce objects
- Desktop integration clients
- Your Salesforce contract
Information for specific feature limits, such as the number of total and active rules in your org, are also in Salesforce Help; see the topics for using that feature. For allocations per edition, see [Salesforce Features and Edition Allocations](https://help.salesforce.com/articleView?id=overview_limits_general.htm). For information on limits when using Salesforce Functions, see [Functions Limits](https://developer.salesforce.com/docs/platform/functions/guide/limits.html). Contractual limits might also apply, as per your Salesforce contract.
# Abstract Components
Object-oriented languages, such as Java, support the concept of an abstract class that provides a partial implementation for an object but leaves the remaining implementation to concrete sub-classes. An abstract class in Java can't be instantiated directly, but a non-abstract subclass can.
Similarly, the Aura Components programming model supports the concept of abstract components that have a partial implementation but leave the remaining implementation to concrete sub-components.
To use an abstract component, you must extend it and fill out the remaining implementation. An abstract component can't be used directly in markup.
The `` tag has a boolean `abstract` attribute. Set `abstract="true"` to make the component abstract.
**See Also**
- [Interfaces](https://developer.salesforce.com/docs/platform/aura-platform/guide/oo-interfaces.md)
# AcademicTermGpaCalcEvent
Represents the resources required for the execution of the academic term GPA calculation policy rule. This object is available in API version 63.0 and later.
## Supported Calls
`create()`, `describeSObjects()`
## Fields
### `AcademicTerm`
**Type:** string
**Properties:** Create
**Description:** Represents the resources required for the execution of the academic term GPA calculation policy rule.
### `EventUuid`
**Type:** string
**Properties:** Nillable
**Description:** A universally unique identifier (UUID) that identifies a platform event message.
### `PolicyRuleApiName`
**Type:** string
**Properties:** Create
**Description:** The developer name of the policy rule used to calculate the academic term grade point average.
### `ReplayId`
**Type:** string
**Properties:** Nillable
**Description:** Represents an ID value that is populated by the system and refers to the position of the event in the event stream. Replay ID values aren’t guaranteed to be contiguous for consecutive events. A subscriber can store a replay ID value and use it on resubscription to retrieve missed events that are within the retention window.
# AcadRgstrApplnEvent
Represents the resources required to apply an academic term registration timeline on an academic term enrollment. This object is available in API version 65.0 and later.
## Supported Calls
`create()`, `describeSObjects()`
## Fields
### `BatchJob`
**Type:** string
**Properties:** Create
**Description:** The identifier of the batch job for the Academic Registration Timeline Eligibility Criteria Run Event.
### `EventUuid`
**Type:** string
**Properties:** Nillable
**Description:** A universally unique identifier (UUID) that identifies a platform event message.
### `ReplayId`
**Type:** string
**Properties:** Nillable
**Description:** Represents an ID value that is populated by the system and refers to the position of the event in the event stream. Replay ID values aren’t guaranteed to be contiguous for consecutive events. A subscriber can store a replay ID value and use it on resubscription to retrieve missed events that are within the retention window.
# AcadRgstrEligCritRunEvent
Represents the resources required to run an eligibility criteria (expression set) calculation on an academic term enrollment for an academic term registration timeline. This object is available in API version 65.0 and later.
## Supported Calls
`create()`, `describeSObjects()`
## Fields
### `AcademicTerm`
**Type:** string
**Properties:** Create
**Description:** The identifier of the academic term on which the eligibility criteria calculation is run.
### `AcademicTermRegstrnTimeline`
**Type:** string
**Properties:** Create
**Description:** The identifier of the Academic Term Registration Timeline for which the eligibility criteria calculation is run.
### `EligibilityCriteriaApiName`
**Type:** string
**Properties:** Create
**Description:** The developer name of the eligibility criteria (expression set) used to calculate the academic term registration timeline for students.
### `EventUuid`
**Type:** string
**Properties:** Nillable
**Description:** A universally unique identifier (UUID) that identifies a platform event message.
### `ReplayId`
**Type:** string
**Properties:** Nillable
**Description:** Represents an ID value that is populated by the system and refers to the position of the event in the event stream. Replay ID values aren’t guaranteed to be contiguous for consecutive events. A subscriber can store a replay ID value and use it on resubscription to retrieve missed events that are within the retention window.
# Accept On-Site Payments with Tap-to-Pay
A Lightning web component can use a mobile device to let your customers use the Tap-to-Pay capability of the Payments plug-in to pay mobile workers directly. The Field Service mobile app then integrates with Pay Now to connect the Lightning web component to a secure payment system that processes the interaction.
The PaymentsService plugin allows Field Service mobile workers to collect payments from their customers using Tap to Pay. This service integrates with Salesforce Payments and Stripe as a payment provider. Tap to Pay is supported on iOS and Android devices with Stripe as the payment provider.
**important:** PaymentsService does not and cannot function when running in a web browser, whether on a desktop or mobile device.
- **[PaymentsService User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-paymentsservice-intro.md)**
Your component can deliver any user experience you want, but you must follow a common flow for any component that calls for a Payment Service.
- **[Use the PaymentsService API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-paymentsservice-in-a-lightning-component.md)**
To develop an LWC with the Payments Service plug-in features, use the Payments Plugin API as your method for accessing a device’s native Tap to Pay functionality.
- **[PaymentsService Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-paymentsservice-example.md)**
Here’s a basic example of a Lightning web component minimal HTML template that includes a button that initiates collecting payment.
- **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-paymentsservice-compatibility.md)**
PaymentsService is a JavaScript module that provides an API to Lightning web components to make mobile hardware and platform (operating system) features available in JavaScript. It **requires** access to device hardware and device platform APIs. This access is only available when PaymentsService runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a standard web browser, whether the browser runs on a desktop or mobile device.**
- **[Considerations and Limitations](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-paymentsservice-considerations.md)**
Consider these guidelines and limitations when developing features that use the PaymentsService API.
**See Also**
- [_Lightning Web Components Developer Guide:_ PaymentsService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-paymentsservice.html)
# Access a Mobile Device’s Biometrics Capabilities
A Lightning web component can use a device’s biometrics functionality to prompt a user to confirm their identity. When these biometrics-related actions occur, the result is returned to the Lightning web component that invoked it.
Biometrics checks are managed locally on the mobile device, and don't need a network connection. However, BiometricsService requires access to platform-specific APIs that are available only within compatible Salesforce mobile apps.
**important:** BiometricsService does not and cannot function when running in a web browser, whether on a desktop or mobile device.
- **[BiometricsService User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-biometricsservice-intro.md)**
Your component can deliver any user experience you desire, but there’s a common flow for any component that calls for a biometrics check.
- **[Use the BiometricsService API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-biometricsservice-in-a-lightning-component.md)**
To develop a Lightning web component with biometrics-checking features, use the BiometricsService API as your method for accessing a device’s native biometrics functionality.
- **[BiometricsService Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-biometricsservice-example.md)**
Here’s a basic example of a Lightning web component that uses a device’s biometrics capabilities to verify device ownership.
- **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-biometricsservice-compatibility.md)**
BiometricsService is a JavaScript module that provides an API to Lightning web components to make mobile hardware and platform (operating system) features available in JavaScript. It **requires** access to device hardware and device platform APIs. This access is only available when BiometricsService runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a standard web browser, whether the browser runs on a desktop or mobile device.**
- **[Considerations and Limitations](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-biometricsservice-considerations.md)**
Consider these guidelines and limitations when developing features that use the BiometricsService API.
**See Also**
- [_Lightning Web Components Developer Guide:_ BiometricsService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-biometricsservice.html)
# Access and Manage Contacts on a Mobile Device
A Lightning web component can use a mobile device’s contacts features to select contacts from the device's address book or save new contacts to it. When contacts are selected, they’re returned to the Lightning web component that invoked it. Your component can then import the contacts into Salesforce, attach contact data to a record, or otherwise process the contacts as needed. Your component can also take contact information from Salesforce and export it to create a new contact on the device.
Contacts are accessed locally on the mobile device, and ContactsService doesn’t require a network connection. However, ContactsService requires access to platform-specific APIs that are available only within compatible Salesforce mobile apps.
**important:** ContactsService does not and cannot function when running in a web browser, whether on a desktop or mobile device.
- **[ContactsService User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-contactsservice-intro.md)**
Your component can deliver any user experience you desire, but there’s a common flow for any component that imports or exports contact data.
- **[Use the ContactsService API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-contactsservice-in-a-lightning-component.md)**
To develop a Lightning web component with contacts-based features, use the ContactsService API as your method for selecting contacts from a device’s address book.
- **[ContactsService Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-contactsservice-example.md)**
Here’s a minimal but complete example of a Lightning web component that uses ContactsService to select on-device contacts and then process the contact data in the component.
- **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-contactsservice-compatibility.md)**
ContactsService is a JavaScript module that provides an API to Lightning web components to make mobile hardware and platform (operating system) features available in JavaScript. It **requires** access to device hardware and device platform APIs. This access is only available when ContactsService runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a standard web browser, whether the browser runs on a desktop or mobile device.**
- **[Considerations and Limitations](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-contactsservice-considerations.md)**
Keep the following in mind when developing features that use the ContactsService API.
**See Also**
- [_Lightning Web Components Developer Guide:_ ContactsService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-contactsservice.html)
# Access Controllers From Visualforce Pages in Different Packages
To access an Apex controller from a Visualforce page that is in a different package, use the `@namespaceAccessible` Apex annotation in your custom controller class. In first-generation packaging, you can develop only one managed package with a given namespace. In second-generation packaging, you can develop more than one managed (or unlocked) package with the same namespace. By default, Visualforce pages installed in a package can't call a public Apex method from an Apex class in another package. This is true even if both packages are in the same namespace.
Here’s an example of how to include the `@namespaceAccessible` annotation in your Apex code.
```apex
@namespaceAccessible
public virtual class NsController {
private String message;
@namespaceAccessible
public NsController() {
this.message = 'default'; // init to non-blank value
}
@namespaceAccessible
public virtual String getMessage() {
return this.message;
}
@namespaceAccessible
public virtual void setMessage(String msg) {
this.message = msg;
}
}
```
First, add the annotation above the controller, which makes it visible from across the namespace in different packages. You must annotate the controller so that any methods you add to the annotation are also visible. Then, for every method that you want visible across the namespace, add the `@namespaceAccessible` annotation before the method. Use the annotation only for methods that you want visible outside of your package, but within the same namespace.
# Access External Data with Data Access Objects
When running Data Loader in batch mode from the command line, several data access objects are supported. allows access to an external data source outside of Salesforce. A data access object can implement a read interface (`DataReader`), a write interface (`DataWriter`), or both.
|Required Editions|
|-----------------|
|Available in: both Salesforce Classic ([not available in all orgs](https://help.salesforce.com/s/articleView?id=xcloud.overview_edition_lex_only.htm&type=5)) and Lightning Experience|
|Available in: **Enterprise**, **Performance**, **Unlimited**, and **Developer** editions|
**note:** The Data Loader command-line interface is supported for Windows only.
Here's a list of object names and descriptions.
- csvRead—Allows the reading of a comma or tab-delimited file. There must be a header row at the top of the file that describes each column.
- csvWrite—Allows writing to a comma-delimited file. A header row is added to the top of the file based on the column list provided by the caller.
- databaseRead—Allows the reading of a database. Use `database-conf.xml` to configure database access.
- databaseWrite—Allows writing to a database. Use `database-conf.xml` to configure database access.
# Access Health Data on a Mobile Device
A Lightning web component can use a mobile device’s health store to read and write a user’s body-weight records. Your component can read weight history to display it in a Salesforce record, or write a new weight measurement back to the device’s health store.
Health data is stored locally on the mobile device, and HealthService doesn’t require a network connection. However, HealthService requires access to platform-specific APIs that are available only within compatible Salesforce mobile apps. On iOS, HealthService reads and writes data through Apple HealthKit. On Android, HealthService uses Android Health Connect.
**important:** HealthService does not and cannot function when running in a web browser, whether on a desktop or mobile device.
- **[HealthService User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-healthservice-intro.md)**
Your component can deliver any user experience you want, but there’s a common flow for any component that reads or writes health data.
- **[Use the HealthService API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-healthservice-in-a-lightning-component.md)**
To develop a Lightning web component with health data features, use the HealthService API to read and write body-weight records on the device.
- **[HealthService Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-healthservice-example.md)**
Here’s a minimal but complete example of a Lightning web component that uses HealthService to write a weight record to the device and read the weight history back again.
- **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-healthservice-compatibility.md)**
HealthService is a JavaScript module that provides an API to Lightning web components to make mobile hardware and platform (operating system) features available in JavaScript. It **requires** access to device hardware and device platform APIs. This access is only available when HealthService runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a standard web browser, whether the browser runs on a desktop or mobile device.**
- **[Considerations and Limitations](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-healthservice-considerations.md)**
Keep these guidelines and limitations in mind when developing features that use the HealthService API.
**See Also**
- [_Lightning Web Components Developer Guide:_ HealthService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-healthservice.html)
# Accessibility for Lightning Base Components
This section explains the accessibility features on components in the `lightning` namespace.
- **[Button Labels](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-buttons.md)**
- **[Audio Messages](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-messages.md)**
- **[Forms, Fields, and Labels](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-forms.md)**
- **[Using Images and Icons](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-img.md)**
- **[Events](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-events.md)**
- **[Menus](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-menus.md)**
# Accessibility Tests Example
If you’ve made a component accessible, write tests to make sure it stays that way. You can write automated tests for a variety of accessibility concerns, including expected keyboard functionality and that the role, state, and property ARIA values for HTML elements are correct.
Let’s look at an example that tests an expandable section. When you click Codey’s name, the section expands to tell you more about him, and when you click his name again, the section collapses.

Here’s some pseudocode for an Aura component test that toggles the collapsed and expanded state of an expandable section.
```javascript
testToggleExpandCollapse : {
test : [
function(cmp) {
// Default: collapsed
this.assertCollapsed(cmp);
// Toggle to expanded
this.clickToggleButton(cmp);
this.assertExpanded(cmp);
// Toggle back to collapsed
this.clickToggleButton(cmp);
this.assertCollapsed(cmp);
}
]
}
```
First, we assert the element is collapsed by default, then we click the toggle button, verify it’s expanded, click the toggle button again, and verify it’s collapsed.
How can we embed accessibility checks into this test? Let’s explore the two helper functions `assertCollapsed` and `assertExpanded`.
```javascript
assertCollapsed : (cmp) {
var button = this.getButton(cmp);
var section = this.getSection(cmp);
// Button indicates section is collapsed
aura.test.assertEquals(
button.getAttribute('aria-expanded'),
"false",
"Button should indicate it's collapsed"
);
// Section is visually closed
aura.test.assertFalse(
section.classname.indexOf('slds-is-open') > -1,
"Section should be collapsed"
);
}
```
For an expandable section to be accessible, it must communicate its expanded or collapsed state to assistive technology users, such as screen reader users. The best way to make the section accessible is with an ARIA state attribute, `aria-expanded`, on the button, which is `true` when the section is expanded and `false` otherwise. To make sure that this attribute is always properly set, we can assert it has the correct value. In `assertCollapsed`, we assert that `aria-expanded` has a value of `false`. Now, in `assertExpanded`, we can assert that aria-expanded has a value of `true`.
```javascript
assertExpanded : (cmp) {
var button = this.getButton(cmp);
var section = this.getSection(cmp);
// Button indicates section is expanded
aura.test.assertEquals(
button.getAttribute('aria-expanded'),
"true",
"Button should indicate it's expanded"
);
// Section is visually open
aura.test.assertTrue(
section.classname.indexOf('slds-is-open') > -1,
"Section should be open"
);
}
```
If the code that’s setting `aria-expanded` regresses, we catch the bug before it reaches screen reader users. Now let’s go back to our `testToggleExpandCollapse` test case. Let’s add `$A.test.assertAccessible()` in two strategic places so that we run Salesforce’s default set of accessibility checks against the section’s expanded and collapsed states. Remember, we want to test every state, not just one. If we test only the collapsed state, we might miss accessibility bugs in the expanded section.
```javascript
testToggleExpandCollapse : {
test : [
function(cmp) {
// Default: collapsed
this.assertCollapsed(cmp);
// Toggle to expanded
this.clickToggleButton(cmp);
this.assertExpanded(cmp);
$A.test.assertAccessible();
// Toggle back to collapsed
this.clickToggleButton(cmp);
this.assertCollapsed(cmp);
$A.test.assertAccessible();
}
]
}
```
Now we have accessibility checks running automatically in our custom tests.
# Accessing Data with a Standard Controller
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.
**note:** 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. If a contact record ID is specified by the `id` query string parameter, no data is returned by the `{!account}` expression.
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.
# Accessing Data with List Controllers
## Access Records with Expression Syntax
Once you have associated a page with a list controller, you can act on a set of records using expression language syntax. For example, to create a table of accounts, use the following markup:
```apex_page
```
This example uses the component `` to generate a table of data. The `value` attribute is set to the variable loaded by the standard list controller, `{!accounts}`, which is the list of records that `` loops through.
For each record in the list, `` assigns the record to the `acc` variable. Then, `` constructs a new row in the table, using the row defined by the `` component. The `` component uses the `acc` variable, which represents the current record, to pull out the field values for that record.
The resulting page that lists all the account names in your organization:

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](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/controller/pages-custom-list-controller.md), you can control the sort method.
**note:** This page does not specify a filter in the request, so the page is displayed with the last used filter. For information on using filters with list controllers, see [List Views with Standard List Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-list-views.md).
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.
## Access Records with IDs
In a typical page interaction, a user selects records from a list view 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.
Let's look at some code. This example uses the markup from the earlier example to display Account names in a table. Then, it includes custom Apex code to request the specific records to display.
```apex
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, define`setController.setSelected(records)` so that the records are selected on page load.
**note:** A standard list controller can return up to 10,000 records. Custom controllers can work with larger results sets. See [Working with Large Sets of Data](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/controller/pages-controller-readonly-context.md).
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.
**See Also**
- [*SOQL and SOSL Reference*: Relationship Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships.htm)
# Accessing Metrics for Your Visualforce Pages
To query metrics on the Visualforce pages in your org, use the `VisualforceAccessMetrics` object in the Salesforce SOAP API.
To query information from the `VisualforceAccessMetrics` object, use the Query Editor in the Developer Console. If you use Visual Studio Code, you can also make queries with the SOQL Builder, which is part of the Salesforce Extension Pack.
The following is a sample SOQL call:
```soql
SELECT ApexPageId, DailyPageViewCount, Id, ProfileId, MetricsDate, LogDate FROM VisualforceAccessMetrics
```
|Parameter|Description|
|---------|-----------|
|`LogDate`|This parameter provides the date that the page access was logged. This parameter is available for release 216 and later.|
|`ProfileId`|The ID of the profile associated with the user who accessed the page. This parameter is available for release 216 and later.|
|`ApexPageId`|The ID of the tracked Visualforce page|
|`DailyPageView`|Each `VisualforceAccessMetrics` object tracks the daily page view count in the `DailyPageViewCount` field.|
|`MetricsDate`|The date the metrics were collected is specified in `MetricsDate`.|
**note:** Page views are tallied the day after the page is viewed, and each `VisualforceAccessMetrics` object is removed after 90 days.
Using `VisualforceAccessMetrics`, you can track the number of views each Visualforce page in your org receives in a 24-hour time period. To find out how many views a page got over the course of multiple days, you can query multiple `VisualforceAccessMetrics` objects for the same `ApexPageId`.
**See Also**
- [*Object Reference for the Salesforce Platform*: VisualforceAccessMetrics](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_visualforceaccessmetrics.htm)
# Action
`Action` contains methods to work with JavaScript actions that you can use to communicate with Apex classes.
## Methods
- **[getError()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-geterror.md)**
Returns an array of error objects for server-side actions only. Each error object has a message field. In any mode except `PROD` mode, each object also has a stack field, which is a list describing the execution stack when the error occurred.
- **[getName()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-getname.md)**
Returns the name of an action.
- **[getParam()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-getparam.md)**
Returns an action parameter value for a parameter name.
- **[getParams()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-getparams.md)**
Returns the collection of parameters for an action.
- **[getReturnValue()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-getreturnvalue.md)**
Gets the return value of an Apex action. An Apex action can return any object containing serializable JSON data.
- **[getState()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-getstate.md)**
Returns the current state of an action. Check the state of the action in the callback after an Apex action completes.
- **[isBackground()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-isbackground.md)**
Returns `true` if the action is enqueued in the background, `false` if it’s enqueued in the foreground.
- **[setAbortable()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setabortable.md)**
Sets an action as abortable. If the component is not valid, abortable actions are not sent to the server. A component is automatically destroyed and marked invalid by the framework when it is unrendered. Actions not marked abortable are always sent to the server regardless of the validity of the component.
- **[setBackground()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setbackground.md)**
Sets the action to run as a background action. This cannot be unset. Background actions are usually long running and lower priority actions. A background action is useful when you want your app to remain responsive to a user while it executes a low priority, long-running action. A rough guideline is to use a background action if it takes more than five seconds for the response to return from the server.
- **[setCallback()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setcallback.md)**
Sets the callback function that is executed after an Apex action returns.
- **[setParam()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setparam.md)**
Sets a single parameter for an action. Use parameters to pass data to an Apex action.
- **[setParams()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setparams.md)**
Sets parameters for an action. Use parameters to pass data to an Apex action.
- **[setStorable()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-action-setstorable.md)**
Marks an Apex action as storable to have its response stored in the framework’s client-side cache . Enhance your component’s performance by marking actions as storable (cacheable) to quickly show cached data from client-side storage without waiting for a server trip. If the cached data is stale, the framework retrieves the latest data from the server. Caching is especially beneficial for users on high latency, slow, or unreliable connections such as 3G networks.
# Action Objects
This is the reference for quick actions and dynamic actions. Invocable actions are also known as dynamic actions.
# Actions and Events
The framework uses events to communicate data between components. Events are usually triggered by a user action.
## Actions
User interaction with an element on a component or app. User actions trigger events, but events aren’t always explicitly triggered by user actions. This type of action is _not_ the same as a client-side JavaScript controller, which is sometimes known as a controller action. The following button is wired up to a browser `onclick` event in response to a button click.
```nolang
```
Clicking the button invokes the `handleClick` method in the component’s client-side controller.
## Events
A notification by the browser regarding an action. Browser events are handled by client-side JavaScript controllers, as shown in the previous example. A browser event is not the same as a framework _component event_ or _application event_, which you can create and fire in a JavaScript controller to communicate data between components. For example, you can wire up the click event of a checkbox to a client-side controller, which fires a component event to communicate relevant data to a parent component.
Another type of event, known as a _system event_, is fired automatically by the framework during its lifecycle, such as during component initialization, change of an attribute value, and rendering. Components can handle a system event by registering the event in the component markup.
The following diagram describes what happens when a user clicks a button that requires the component to retrieve data from the server.

1. User clicks a button or interacts with a component, triggering a browser event. For example, you want to save data from the server when the button is clicked.
2. The button click invokes a client-side JavaScript controller, which provides some custom logic before invoking a helper function.
3. The JavaScript controller invokes a helper function. A helper function improves code reuse but it’s optional for this example.
4. The helper function calls an Apex controller method and queues the action.
5. The Apex method is invoked and data is returned.
6. A JavaScript callback function is invoked when the Apex method completes.
7. The JavaScript callback function evaluates logic and updates the component’s UI.
8. User sees the updated component.
**See Also**
- [Handling Events with Client-Side Controllers](https://developer.salesforce.com/docs/platform/aura-platform/js/js-client-side-controller.md)
- [Detecting Data Changes with Change Handlers](https://developer.salesforce.com/docs/platform/aura-platform/js-cb/js-cb-data-change.md)
- [Calling a Server-Side Action](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-actions-call.md)
- [Events Fired During the Rendering Lifecycle](https://developer.salesforce.com/docs/platform/aura-platform/components/components-lifecycle.md)
# Actions Developer Guide Previous PDF Versions
| API Version | Release | PDF |
| ----------- | ---------- | ---------------------------------------------------------------------------------------------- |
| 68.0 | Winter '27 | [Download PDF](https://resources.docs.salesforce.com/264/latest/en-us/sfdc/pdf/api_action.pdf) |
| 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/api_action.pdf) |
| 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/api_action.pdf) |
| 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/api_action.pdf) |
# Add a Canvas App to a Page Layout
Add a canvas app to the page layout for an Account.
1. To create a canvas app, follow the steps in [Create the App](https://developer.salesforce.com/docs/platform/quick-start-simple/quick-start-simple-create-app.md).
2. From Setup, enter `Apps` in the Quick Find box, then select **Manage Connected Apps**.
3. In the Connected Apps list view, click **Edit** next to the app that you created.
4. In the Canvas Apps Settings section, in the Locations field, select **Layouts and Mobile Cards**.
5. Click **Save**.
6. From Setup, click **Object Manager**, then select **Account**.
7. On the Account object management page, click **Page Layouts**, then click **Account Layout**.

The Canvas Apps category is in the palette and the canvas app because you set the location of the canvas app to Layouts and Mobile Cards.
8. Drag the canvas app element to where you want it to appear in the page layout, and then click **Save**.
- If you add the canvas app to any section other than the Mobile Cards section, the canvas app appears in the page layout in the full Salesforce site or in the record detail page in the Salesforce mobile app.
- If you add the canvas app to the Mobile Cards section, the canvas app appears only in the mobile card.
9. To see your changes, click the **Accounts** tab, and then click an account.
You can modify additional properties of the canvas app in the page layout by clicking the wrench icon .
- `Width (in pixels or %)`—The width of the canvas app; defaults to 100%. Changes to the width of the canvas app appear in both the full Salesforce site and the Salesforce mobile app. However, canvas apps are displayed in a single-column layout, so we recommend that you leave the width at 100%.
- `Height (in pixels)`—The height of the canvas app; defaults to 200 pixels. Changes to this field appear to the user for canvas apps that appear in both the full Salesforce site and the Salesforce mobile app.
- `Show scrollbars`—Whether scrollbars are displayed on the canvas app iFrame. Changes to this field render for canvas apps that appear in the full Salesforce site but not for canvas apps that appear in the Salesforce mobile app.
- `Show label`—Whether to display the page layout section label. Changes to this field appear to the user for canvas apps that appear in both the full Salesforce site and in the Salesforce mobile app.
**See Also**
- [Canvas Apps in a Page Layout or a Mobile Card](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-framework-using-pl-intro.md)
- [Where Canvas Apps Appear in a Page Layout](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-in-pl-where-can-appear.md)
- [*Salesforce Help*: Find Object Management Settings](https://help.salesforce.com/HTViewHelpDoc?id=extend_click_find_objectmgmt_parent.htm)
# Add a Filter with Metadata API
We recommend using Metadata API as part of the application lifecycle management process to develop, test, deploy, and release your apps to production. If you want to create the channel and filter expression, we recommend that you use Tooling API with REST.
|User Permissions Needed| |
|-----------------------|--|
|To deploy and retrieve metadata types:|Customize Application|
|To update metadata types:|Modify Metadata Through Metadata API Functions|
|To use Metadata API:|API Enabled|
Create a channel and channel member in Metadata API using API version 56.0 or later.
To create a channel and channel member with Metadata API, you can use tools such as Visual Studio Code with the Salesforce Extension pack or Salesforce CLI. For more information, see [Metadata API Developer Tools](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_developer_tools.htm) and [Quick Start: Metadata API](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_quickstart_retrieve.htm) in the *Metadata API Developer Guide*.
The steps are based on a custom channel. We recommend using a custom channel instead of the standard channel so that the filtered stream is isolated from the standard event stream and subscribers expect the stream to be filtered. You can alternatively use the ChangeEvents standard channel. If you do so, you can skip the custom channel definition, and for the PlatformEventChannelMember definition, adjust the file name and use this `eventChannel` value: `ChangeEvents`.
This sample custom channel definition is for the `FilteredChannel__chn` channel. The file name is FilteredChannel__chn.platformEventChannel.
```nolang
data
```
Next, add a channel member. This channel member specifies the enriched fields of Industry and NumberOfEmployees, the filter expression, and the selected entity of AccountChangeEvent. The file name is `FilteredChannel_chn_AccountChangeEvent.platformEventChannelMember`.
```nolang
FilteredChannel__chn1000]]>AccountChangeEvent
```
**note:** If the filter expression contains the `<` and `&` special characters, they aren’t allowed in XML data in their literal form. Escape those characters as `<` and `&`, or enclose the entire filter expression value within the `` section. Although no special characters are present in the previous example, `` is included for convenience. For more information, see [CData sections](https://www.w3.org/TR/xml/#sec-cdata-sect) in the Extensible Markup Language (XML) specification.
If your Salesforce org has a namespace, prepend the namespace prefix to each field used in `filterExpression` and the `selectedEntity` value in the PlatformEventChannelMember request body. For example, if the namespace is `ns`, the request body in this example becomes:
```nolang
FilteredChannel__chn1000]]>AccountChangeEvent
```
This `package.xml` file references the channel and channel member.
```nolang
FilteredChannel__chnPlatformEventChannelFilteredChannel_chn_AccountChangeEventPlatformEventChannelMember68.0
```
To update a filter expression, redeploy the package with an updated value for the `filterExpression` field in the PlatformEventChannelMember component. You can update only the filter expression and enriched fields of a channel member. All other fields aren’t updateable.
You can add another filter on another change event by adding a channel member to the same channel. For example, to filter lead change events, add a second channel member for the `FilteredChannel__chn` channel. In this member, specify `selectedEntity` as LeadChangeEvent, and specify the filter expression and enriched fields. This PlatformEventChannelMember definition is an example component with a file name of `FilteredChannel_chn_LeadChangeEvent.platformEventChannelMember`.
```nolang
FilteredChannel__chn1000000]]>LeadChangeEvent
```
This `package.xml` file references both channel members.
```nolang
FilteredChannel__chnPlatformEventChannelFilteredChannel_chn_AccountChangeEventFilteredChannel_chn_LeadChangeEventPlatformEventChannelMember68.0
```
**See Also**
- [*Metadata API Developer Guide*: PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannel.htm)
- [*Metadata API Developer Guide*: PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannelmember.htm)
# Add a Filter with Metadata API
We recommend using Metadata API as part of the application lifecycle management process to develop, test, deploy, and release your apps to production. If you want to create the channel and filter expression, we recommend that you use Tooling API with REST.
|User Permissions Needed| |
|-----------------------|--|
|To deploy and retrieve metadata types:|Customize Application|
|To update metadata types:|Modify Metadata Through Metadata API Functions|
|To use Metadata API:|API Enabled|
Before you add a filter, create a channel. Use PlatformEventChannel in Metadata API, and specify API version 56.0 or later.
To create a channel and channel member with Metadata API, you can use tools such as Visual Studio Code with the Salesforce Extension pack or Salesforce CLI. For more information, see [Metadata API Developer Tools](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_developer_tools.htm) and [Quick Start: Metadata API](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_quickstart_retrieve.htm) in the *Metadata API Developer Guide*.
This sample custom channel definition is for the `MyChannel__chn` channel. The file name is MyChannel__chn.platformEventChannel. To have this channel accept platform events, `event` is specified for `channelType`.
```nolang
event
```
This channel member specifies the custom platform event and filter expression. This sample channel member definition associates the custom platform event to the channel and adds a filter expression. The file name is `MyChannel_chn_Order_Event_e.platformEventChannelMember`.
```nolang
MyChannel__chn10.50]]>
Order_Event__e
```
**note:** If the filter expression contains the `<` and `&` special characters, they aren’t allowed in XML data in their literal form. Escape those characters as `<` and `&`, or enclose the entire filter expression value within the `` section. Although no special characters are present in the previous example, `` is included for convenience. For more information, see [CData sections](https://www.w3.org/TR/xml/#sec-cdata-sect) in the Extensible Markup Language (XML) specification.
If your Salesforce org has a namespace, prepend the namespace prefix to each field used in `filterExpression` and the `selectedEntity` value in the PlatformEventChannelMember request body. For example, if the namespace is `ns`, the request body in this example becomes:
```nolang
MyChannel__chn10.50]]>
ns__Order_Event__e
```
This package.xml file references the channel and channel member.
```nolang
MyChannel__chnPlatformEventChannelMyChannel_chn_Order_Event_ePlatformEventChannelMember68.0
```
To update a filter expression, redeploy the package with an updated value for the `filterExpression` field in the PlatformEventChannelMember component. You can update only the `filterExpression` field of a channel member. All other fields aren’t updateable.
**See Also**
- [*Metadata API Developer Guide*: PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannel.htm)
- [*Metadata API Developer Guide*: PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannelmember.htm)
# Add a Filter with Tooling API
Create a channel and channel member in Tooling API using API version 56.0 or later.
| User Permissions Needed | |
| -------------------------------------------------------------------------------- | --------------------- |
| To create or update PlatformEventChannel and PlatformEventChannelMember objects: | Customize Application |
| To use REST API: | API Enabled |
You can use your preferred REST API tool to perform these steps. We recommend using Postman with the Salesforce Platform APIs collection, which contains handy templates for Salesforce API calls. See [Quick Start: Connect Postman to Salesforce](https://trailhead.salesforce.com/content/learn/projects/quick-start-connect-postman-to-salesforce) in Trailhead.
The steps are based on a custom channel. We recommend using a custom channel instead of the standard channel so that the filtered stream is isolated from the standard event stream and subscribers expect the stream to be filtered. You can alternatively use the ChangeEvents standard channel. If you do so, you can skip steps 1 and 2, and in step 4, adjust the `FullName` field and use this `eventChannel` value: `"eventChannel": "ChangeEvents"`.
1. To create a channel, send a POST request to this URI.
```nolang
/services/data/v68.0/tooling/sobjects/PlatformEventChannel
```
If you're using Postman, expand **Event Platform** | **Custom Channels** | **Platform Event**, and then click **Create channel**.
2. Use this example request body. The `channelType` is `data` because this is a channel for change events.
```nolang
{
"FullName": "FilteredChannel__chn",
"Metadata": {
"channelType": "data",
"label": "My Custom Filtered Channel"
}
}
```
You receive a response similar to this example response.
```nolang
{
"id" : "0YLRM000000004m4AA",
"success" : true,
"errors" : [ ],
"warnings" : [ ],
"infos" : [ ]
}
```
3. Add a channel member that specifies the Industry field as an enriched field, a change event type of AccountChangeEvent, and a filter expression.
```nolang
/services/data/v68.0/tooling/sobjects/PlatformEventChannelMember
```
If you're using Postman, expand **Event Platform** | **Custom Channels** | **Platform Event**, and then click **Create channel member**.
4. Use this example request body.
```nolang
{
"FullName": "FilteredChannel_chn_AccountChangeEvent",
"Metadata": {
"eventChannel": "FilteredChannel__chn",
"filterExpression": "Industry='Agriculture' AND NumberOfEmployees>1000",
"selectedEntity": "AccountChangeEvent"
}
}
```
You receive a response similar to this example response.
```nolang
{
"id" : "0v8RM0000004VAKYA2",
"success" : true,
"errors" : [ ],
"warnings" : [ ],
"infos" : [ ]
}
```
To update a filter expression, perform a PATCH request to `/services/data/v`68.0`/tooling/sobjects/PlatformEventChannelMember/`, and pass in the entire request body with the new filter expression. You can update only the filter expression and enriched fields of a channel member. All other fields aren’t updateable.
If your Salesforce org has a namespace, prepend the namespace prefix to each field used in `filterExpression` and the `selectedEntity` value in the PlatformEventChannelMember request body. For example, if the namespace is `ns`, the request body in this example becomes:
```nolang
{
"FullName": "FilteredChannel_chn_AccountChangeEvent",
"Metadata": {
"eventChannel": "FilteredChannel__chn",
"filterExpression": "ns__Industry='Agriculture' AND ns__NumberOfEmployees>1000",
"selectedEntity": "AccountChangeEvent"
}
}
```
You can add another filter to the same channel for another change event by adding another channel member. For example, if you want to filter lead change events, add a second channel member for the `FilteredChannel__chn` channel. In this member, specify `selectedEntity` as `LeadChangeEvent`, and specify the filter expression. For example:
```nolang
{
"FullName": "FilteredChannel_chn_LeadChangeEvent",
"Metadata": {
"eventChannel": "FilteredChannel__chn",
"filterExpression": "AnnualRevenue>1000000",
"selectedEntity": "LeadChangeEvent"
}
}
```
**See Also**
- [_Tooling API Developer Guide_: PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannel.htm)
- [_Tooling API Developer Guide_: PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannelmember.htm)
# Add a Filter with Tooling API
Before you can add a filter, create a channel. Use PlatformEventChannel in Tooling API, and specify API version 56.0 or later.
## Before You Begin
|User Permissions Needed| |
|-----------------------|--|
|To create or update PlatformEventChannel and PlatformEventChannelMember objects:|Customize Application|
|To use REST API:|API Enabled|
You can use your preferred REST API tool to perform these steps. We recommend using Postman with the Salesforce Platform APIs collection, which contains handy templates for Salesforce API calls. To set up Postman, see [Quick Start: Connect Postman to Salesforce](https://trailhead.salesforce.com/content/learn/projects/quick-start-connect-postman-to-salesforce) in Trailhead.
1. To create a channel, send a POST request to this URI.
```nolang
/services/data/v68.0/tooling/sobjects/PlatformEventChannel
```
If you're using Postman, expand **Event Platform** | **Custom Channels** | **Platform Event**, and click **Create channel**.
2. Use this example request body. To have this channel accept platform events, `event` is specified for `channelType`.
```nolang
{
"FullName": "MyChannel__chn",
"Metadata": {
"channelType": "event",
"label": "Custom Channel for Platform Events"
}
}
```
You receive a response similar to this example response.
```nolang
{
"id" : "0YLRM000000004X4AQ",
"success" : true,
"errors" : [ ],
"warnings" : [ ],
"infos" : [ ]
}
```
3. Add a channel member that specifies the custom platform event and filter expression. This example references the custom platform event, Order_Event__e. Send a POST request to this URI.
```nolang
/services/data/v68.0/tooling/sobjects/PlatformEventChannelMember
```
If you're using Postman, expand **Event Platform** | **Custom Channels** | **Platform Event**, and click **Create channel member**.
4. Use this example request body.
```nolang
{
"FullName": "MyChannel_chn_Order_Event_e",
"Metadata": {
"eventChannel": "MyChannel__chn",
"filterExpression": "(City__c LIKE 'S%' OR City__c='New York') AND Amount__c>10.50",
"selectedEntity": "Order_Event__e"
}
}
```
You receive a response similar to this example response.
```nolang
{
"id" : "0v8RM0000000MnNYAU",
"success" : true,
"errors" : [ ],
"warnings" : [ ],
"infos" : [ ]
}
```
## Next Steps
To update a filter expression, perform a PATCH request to `/services/data/v68.0/tooling/sobjects/PlatformEventChannelMember/`, and pass in the entire request body with the new filter expression. You can update only the `filterExpression` field of a channel member. All other fields aren’t updateable.
If your Salesforce org has a namespace, prepend the namespace prefix to each field used in `filterExpression` and the `selectedEntity` value in the PlatformEventChannelMember request body. For example, if the namespace is `ns`, the request body in this example becomes:
```nolang
{
"FullName": "MyChannel_chn_Order_Event_e",
"Metadata": {
"eventChannel": "MyChannel__chn",
"filterExpression": "(ns__City__c LIKE 'S%' OR ns__City__c='New York') AND ns__Amount__c>10.50",
"selectedEntity": "ns__Order_Event__e"
}
}
```
**See Also**
- [*Tooling API Developer Guide*: PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannel.htm)
- [*Tooling API Developer Guide*: PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannelmember.htm)
# Add a Geocode to a Custom Address Field
The method to get geocodes differs between standard and custom address fields. To give your users precise geographical information, add geocode information to a custom address field with Apex, Visualforce, and a map API.
||
|-|
|Available in: both Salesforce Classic ([not available in all orgs](https://help.salesforce.com/s/articleView?id=xcloud.overview_edition_lex_only.htm)) and Lightning Experience|
|Available in: all editions|
|User Permissions Needed| |
|-----------------------|--|
|To modify user interface settings:|Customize Application|
1. Create an Apex class that retrieves latitude and longitude from your preferred map API. This example calls the Google Map API as defined in the String variable `endpoint`.
```trigger
public class GeoCodeExample {
@future(callout=true)
public static void parseJSONResponse() {
double lat;
double lng;
String city = null;
String street = null;
String stateCode = null;
String countryCode = null;
Account record = [SELECT Mailing_Address__c FROM Account WHERE Id = 'Account ID'];
Address customAddress = record.Mailing_Address__c;
//Remove white spaces from address components
if(customAddress.getCity() != null){
city = customAddress.getCity().deleteWhitespace();
}
if(customAddress.getStreet() != null){
street = customAddress.getStreet().deleteWhitespace();
}
if(customAddress.getStateCode() != null){
stateCode = customAddress.getStateCode();
}
if(customAddress.getCountryCode() != null){
countryCode = customAddress.getCountryCode();
}
//concatenate strings
String address = street+city+stateCode+countryCode;
String key='API key';
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
// USING GOOGLE MAP API
String endpoint = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&key='+key;
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
// Parse JSON response to get all the totalPrice field values.
JSONParser parser = JSON.createParser(response.getBody());
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'lat')) {
parser.nextToken();
// Get latitude
lat = parser.getDoubleValue();
parser.nextToken();
parser.nextToken();
//Get longitude
lng = parser.getDoubleValue();
}
}
// Update lat long of account record
record.Mailing_Address__Latitude__s=lat;
record.Mailing_Address__Longitude__s=lng;
update record;
}
}
```
2. Create a Visualforce page that triggers the geocode service from the map API.
```trigger
```
3. On the Visualforce page, click **Get GeoCode For Custom Address Field** to trigger the code. To see the latitude and longitude values populated, query the account information in Developer Console.

To automate the process of updating custom address fields with latitude and longitude, set up a trigger to invoke the Apex class.
**note:** The example in this topic uses a third-party map API to retrieve latitude and longitude. Using a Salesforce trigger to invoke this Apex class calls the map API each time the class is invoked. This action can result in charges from your API provider.
# Add a Trace Flag Entry for the Default Automated Process User
To collect logs for an event subscription, add a trace flag entry for the Automated Process entity in Setup.
1. From Setup, in the Quick Find box, enter `Debug Logs`, then click **Debug Logs**.
2. Click **New**.
3. For Traced Entity Type, select **Automated Process**.
4. Select the time period to collect logs. The start and expiration dates default to the current date and time. To extend the expiration date, click the end date input box, and select the next day from the calendar.
5. For Debug Level, click **New Debug Level**. Enter a name, such as `CustomDebugLevel`, and accept the defaults.
6. Click **Save**.
## Next Steps
To collect logs for the user who publishes the events, add another trace flag entry for that user.
# Add a Trace Flag Entry for the Overridden User
To collect logs for an Apex trigger whose default running user is overridden, add a trace flag entry for the user in Setup.
1. From Setup, in the Quick Find box, enter `Debug Logs`, then click **Debug Logs**.
2. Click **New**.
3. Keep the Traced Entity Type value of `User`.
4. For Traced Entity Name, click the Lookup button, search for the user in the Lookup window, and select it.
5. Select the time period to collect logs. The start and expiration dates default to the current date and time. To extend the expiration date, click the end date input box, and select the next day from the calendar.
6. For Debug Level, click **New Debug Level**. Enter a name, such as `CustomDebugLevel`, and accept the defaults.
7. Click **Save**.
## Next Steps
To collect logs for the user who publishes the events, add another trace flag entry for that user.
# Add an Apex Trigger
The quick start adds a simple change event trigger that shows how to access header and record fields in a change event message.
Before you add and test the trigger, set up debug logging for the Automated Process entity and enable Account for Change Data Capture. See [Prerequisites](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-apex-triggers-prereqs.md).
1. In the Developer Console, select **File** | **New** | **Apex Trigger**.
2. In the Name field, enter a name for the trigger: `MyAccountChangeTrigger`.
3. From the dropdown, select the change event object for Account: **AccountChangeEvent**.
The trigger is created with the `after insert` keyword.
4. Replace the default content of the trigger with the following code.
```apex
trigger MyAccountChangeTrigger on AccountChangeEvent (after insert) {
List tasks = new List();
// Iterate through each event message.
for (AccountChangeEvent event : Trigger.New) {
// Get some event header fields
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
System.debug('Received change event for ' + header.entityName +
' for the ' + header.changeType + ' operation.');
// Get account record fields
System.debug('Account Name: ' + event.Name);
System.debug('Account Phone: ' + event.Phone);
// Create a followup task
if (header.changetype == 'CREATE') {
Task tk = new Task();
tk.Subject = 'Follow up on new account for record or group of records: ' +
header.recordIds;
// Explicitly set the task owner ID to a valid user ID so that
// it is not Automated Process.
// For simplicity, we set it to the CommitUser header field,
// which is available for all operations.
tk.OwnerId = header.CommitUser;
tasks.add(tk);
}
else if ((header.changetype == 'UPDATE')) {
// For update operations, iterate over the list of changed fields
System.debug('Iterate over the list of changed fields.');
for (String field : header.changedFields) {
if (null == event.get(field)) {
System.debug('Deleted field value (set to null): ' + field);
} else {
System.debug('Changed field value: ' + field +
'. New Value: ' + event.get(field));
}
}
}
}
// Insert all tasks in bulk.
if (tasks.size() > 0) {
insert tasks;
}
}
```
This simple trigger writes header and field values to the debug log for each received change event message. The trigger uses the `changedFields` header field to determine which fields changed in an update operation. The trigger also creates a follow-up task for new accounts.
**note:** The `changedFields` property is available in Apex saved using API version 47.0 or later.
5. To test the trigger, create an account with a name and phone.
6. Edit the account, change the name, delete the phone value, and save the record.
7. In Setup, enter `Debug Logs` in the Quick Find box, then select **Debug Logs**.
8. To view the debug logs corresponding to the record creation, click the second log in the list (logs are ordered by most recent first). The output of the `System.debug` statements looks similar to the following.
```apex
...|DEBUG|Received change event for Account for the CREATE operation.
...|DEBUG|Account Name: Quick Start Account
...|DEBUG|Account Phone: 4155551212
```
9. To view the debug logs corresponding to the record update, click the first log in the list. The output of the `System.debug` statements looks similar to the following. The account name’s new value is listed. The phone field’s value was deleted, and its value was set to null. Also, because the system updates the `LastModifiedDate` field when the record is updated, this field is listed in the `changedFields` field and is part of the debug output.
```apex
...|DEBUG|Received change event for Account for the UPDATE operation.
...|DEBUG|Account Name: Quick Start Account Updated
...|DEBUG|Account Phone: null
...|DEBUG|Iterate over the list of changed fields.
...|DEBUG|Changed field value: Name. New Value: Quick Start Account Updated
...|DEBUG|Deleted field value (set to null): Phone
...|DEBUG|Changed field value: LastModifiedDate. New Value: 2019-08-14 23:20:15
```
# Add Attachments to a Visualforce Email Template
You can add attachments to your Visualforce email templates. Each attachment is encapsulated within a single `` component. Code within `` can be a combination of HTML and Visualforce tags.
The example in [Create a Visualforce Email Template](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-email-templates-creating.md) shows how to create a Visualforce email template by iterating through some data and displaying it to an email recipient.
1. To create an attachment that contains the data from the example, use the `` component. This attachment is an unformatted text file.
```apex_page
Dear {!recipient.name},
Attached is a list of cases related to {!relatedTo.name}.
For more detailed information, log in to Salesforce.com
Case Number: {!cx.CaseNumber}
Origin: {!cx.Origin}
Creator Email: {!cx.Contact.email}
Case Number: {!cx.Status}
```
2. To define the name of the attached file, set the `filename` attribute. While it’s good practice to define an easily identifiable name, it isn’t required. If you leave the name undefined, Salesforce generates a name for you. A file name without an extension defaults to a text file.
To render the attached file as a CSV, add the .csv file extension to the file name.
```visualforce
{!cx.CaseNumber}
{!cx.Origin}
{!cx.Contact.email}
{!cx.Status}
```
To render the attached file as an HTML file, add the .html file extension to the file name.
```visualforce
```
Although you can define only one file name for every `` component, you can attach multiple files to an email.
3. To render the attachment as a PDF, set the [`renderAs`](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/styling/pages-output-pdf-renderas.md) attribute to `"PDF"`. Before using this feature, review the [Visualforce PDF Rendering Considerations and Limitations.](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/styling/pages-output-pdf-considerations.md)
```visualforce
You can display your {!relatedTo.name} cases as a PDF:
```
**note:** The `renderAs` attribute accepts any MIME type as a valid value. However, Visualforce supports only PDF rendering. Visualforce doesn’t generate other file formats. It only sets the `Content-Type` field of the HTTP response header to the specified MIME type. Some file formats, such as .xlsx, can fail to render.
4. You can also style your attachment with images or style sheets. Styles are associated with attachments [the same way as they are in Visualforce email templates](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-email-templates-stylesheets.md), either as inline code or by using a custom component.
Attachments rendered as PDFs can reference static resources through the [`$Resource` global variable](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/resources/pages-resources.md), so you can refer to an image or style sheet within the body of the PDF.
For example, this attachment includes a logo in the PDF:
```visualforce
...
```
This attachment references a style sheet that’s saved as a static resource:
```visualforce
...
```
**note:** Referencing static resources on a remote server can increase the time it takes to render a PDF attachment.
You can’t reference remote resources when creating PDF attachments in an Apex trigger. Doing so results in an exception.
# Add Aura Components as Custom Tabs in a Lightning Experience App
Make your Aura components available for Lightning Experience users on desktop and in the Salesforce mobile app by displaying them in a custom tab in a Lightning Experience app.
Before you begin, ensure that your component is configured for custom tab usage. See [Configure Components for Custom Tabs](https://developer.salesforce.com/docs/platform/aura-platform/guide/components-using-lex-s1-config-tab.md).
Follow these steps to include your component in a Lightning Experience app and make it available to desktop and mobile users in your org.
1. Create a custom tab for the component.
1. From Setup, enter `Tabs` in the Quick Find box, then select **Tabs**.
2. Click **New** in the Lightning Component Tabs related list.
3. Select the Lightning component that you want to make available to users.
4. Enter a label to display on the tab.
5. Select the tab style and click **Next**.
6. When prompted to add the tab to profiles, accept the default and click **Save**.
Your Lightning component is now available from the All Items section of the App Launcher on desktop, and the All Items navigation menu item in the Salesforce mobile app.
2. Add your Lightning components to a Lightning app’s navigation.
1. From Setup, enter `Apps` in the Quick Find box, then select **App Manager**.
2. Edit an existing app or create a new app.
3. On the Navigation Items screen, select your Lightning component tab from the Available Items list and move it to the Selected Items list.
4. Save the app.
3. To check your output, navigate to the App Launcher in Lightning Experience on desktop or in the Salesforce mobile app. Select the custom app to see the components that you added.
# Add Components to Apps
When you’re ready to add components to your app, first look at the built-in base components that Salesforce provides with the framework. You can also use these components by extending them or using composition to add them to custom components that you’re building.
**note:** For all the base components, see the [Lightning Component Library](https://developer.salesforce.com/docs/platform/aura-platform/components/component-library.md). The `lightning` namespace includes many base components that implement visual elements common on web pages.
If you can’t find a base component that meets your requirements, consider these options.
- Use [ design variations](https://developer.salesforce.com/docs/platform/aura-platform/slds/lightning-base-variants.md) on base components.
- Apply [utility classes](https://www.lightningdesignsystem.com/utilities/alignment/) or custom CSS classes.
- Combine smaller base components into a more complex, custom component.
- Create your custom component from [Lightning Design System blueprints](https://www.lightningdesignsystem.com/components/overview/).
Components are encapsulated and their internals stay private, while their public shape is visible to consumers of the component. This strong separation gives component authors freedom to change the internal implementation details and insulates component consumers from those changes.
The public shape of a component is defined by the attributes that can be set and the events that interact with the component. The shape is essentially the API for developers to interact with the component. To design a new component, think about the attributes that you want to expose and the events that the component can initiate or respond to.
After you’ve defined the shape of any new components, developers can work on the components in parallel. This approach is useful if you have a team working on an app.
To add a custom component to your app, see [Using the Developer Console](https://developer.salesforce.com/docs/platform/aura-platform/intro/intro-devconsole.md).
**See Also**
- [Component Composition](https://developer.salesforce.com/docs/platform/aura-platform/components/components-composition.md)
- [Using Object-Oriented Development](https://developer.salesforce.com/docs/platform/aura-platform/oo/oo-intro.md)
- [Component Attributes](https://developer.salesforce.com/docs/platform/aura-platform/components/components-attributes.md)
- [Communicating with Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-intro.md)
# Add Links to Lightning Pages from Your Custom Components
To link to Lightning Experience pages, use `lightning:formattedUrl` in your custom component. The `lightning:formattedUrl` component displays a URL as a hyperlink.
## Avoid Full Page Reloads
If you use raw anchor tags or the `ui:outputUrl` (deprecated) component for links, the page does a full reload each time you click the link. To avoid full page reloads, replace your link components with `lightning:formattedUrl`.
For examples, see the [Component Library](https://developer.salesforce.com/docs/component-library/bundle/lightning:formattedUrl/example).
## Migrate from ui:outputUrl to lightning:formattedUrl
Copy the attributes from the `ui:outputUrl` component.
```nolang
```
Paste the same attributes into the `lightning:formattedUrl` component. `lightning:formattedUrl` supports more attributes, like `tooltip`.
```nolang
```
**See Also**
- [*Component Library*: lightning:formattedUrl Reference](https://developer.salesforce.com/docs/component-library/bundle/lightning:formattedUrl/documentation)
# Add LWC Quick Actions to Mobile Layouts
For a quick action to appear in the action bar of a record view, it must be assigned to the main page layout for the record's object type.

Here's an example of assigning the Edit quick action for the Account object type:
1. From Setup, open the **Object Manager**.
2. Enter `Account` in the Quick Find box, then select **Account**.
3. From the Account object management settings, go to **Page Layouts** and click **Account Layout**.
4. In the **Salesforce Mobile and Lightning Experience Actions** panel, if you see a link to override the predefined actions, the page layout is using the default actions. Click the link to enable customizing the actions.
# Add or Change the Translation of a Survey Field
If a survey field can be translated or is already translated into a particular language, you can add or change the translated value of the survey field. This resource is available in REST API version 48.0 and later.
**note:** This URI can only be used for the flow process type `Survey`.
## Syntax
**URI:** `/services/data/vXX.X/localizedvalue/record/developerName/language`
**Formats:** JSON
**HTTP methods:** POST
**Authentication:** `Authorization: Bearer token`
**Request body JSON example**
```nolang
{
"value": "China"
}
```
**Request parameters**
|Parameter|Description|
|---------|-----------|
|`developerName`|Optional. Developer name of the flow field.|
|`language`|Optional Translated language of the flow field.|
|`value`|Required. Translated value of the flow field.|
**Response parameters**
|Parameter|Description|
|---------|-----------|
|`createdBy`|ID of the user who translated the flow field.|
|`createdDate`|Date and time the flow field was translated.|
|`developerName`|Developer name of the flow field.|
|`language`|Language into which the flow field was translated.|
|`value`|Translated value of the flow field.|
|`isOutofDate`|Indicates if the flow field is out of date.|
## Example
```nolang
{
"createdBy": "005xxx",
"createdDate": "2018-09-14T00:10:30Z",
"developerName": "Flow.Flow.MyFlow.1.Choice.Choice_1_Master.InputLabel",
"language": "zh_CN",
"value": "中國",
"isOutOfDate": true
}
```
# Add or Update the Translated Value of Multiple Survey Fields in One or More Languages
If one or more survey fields can be translated or are already translated, you can add or update the translated values of the survey fields in the languages into which survey fields can be translated. This resource is available in REST API version 48.0 and later.
**note:** This URI can only be used for the flow process type `Survey`.
## Syntax
**URI:** `/services/data/vXX.X/localizedvalue/records/upsert`
**Formats:** JSON
**HTTP methods:** POST
**Request body JSON example**
```nolang
[
{
"developerName": "Flow.Flow.MyFlow.1.Choice.Choice_1_Master.InputLabel",
"language": "en_US",
"value": "China"
},
{
"developerName": "Flow.Flow.MyFlow.1.Choice.Choice_1_Master.InputLabel",
"language": "zh_CN",
"value": "中國"
}
]
```
**Request parameters**
|Parameter|Description|
|---------|-----------|
|`developerName`|Required. Developer name of the flow field.|
|`language`|Required. Language into which the flow field is translated.|
|`value`|Required. New or updated value of the flow field.|
**Response parameters**
|Parameter|Description|
|---------|-----------|
|`createdBy`|ID of the user who translated the flow field.|
|`createdDate`|Date and time the flow field was translated.|
|`developerName`|Developer name of the flow field.|
|`language`|Language into which the flow field was translated.|
|`value`|Updated value of the flow field.|
|`isOutofDate`|Indicates if the flow field is out of date.|
## Example
```nolang
[
{
"createdBy": "005xxx",
"createdDate": "2018-09-14T00:10:30Z",
"developerName": "Flow.Flow.MyFlow.1.Choice.Choice_1_Master.InputLabel",
"language": "en_US",
"value": "China",
"isOutOfDate": false
},
{
"createdBy": "005xxx",
"createdDate": "2018-09-14T00:10:30Z",
"developerName": "Flow.Flow.MyFlow.1.Choice.Choice_1_Master.InputLabel",
"language": "zh_CN",
"value": "中國",
"isOutOfDate": false
}
]
```
# Add Pardot Tracking to Your Experience Builder Site
Pardot can track visitor interactions and activities on a site, even when the visitors haven’t yet been converted to a prospect. After tracking is enabled, use Pardot to view reports on visitor engagement, and automatically score leads based on-site activity.
1. In Pardot, navigate to the campaign you want to track.
2. Click **View Tracking Code**, and copy the code.
3. Access Experience Builder of the site you want to add tracking to.
4. In **Settings** | **Advanced**, click **Edit Head Markup**, then paste in the Pardot tracking code.
Experience Builder sites are a single-page apps (SPA), so when the user navigates to different pages on the site, only the content area reloads rather than the entire page. The Pardot script records the first load of the site as a page view. Modify the script to allow in-app navigation within the page to be captured more accurately in Pardot.
1. In the Edit Head Markup window, modify the Pardot tracking code so that changes in page state are added to the session history.
Here’s a sample code snippet with modifications noted.
```javascript
```
Update your site’s Content Security Policy (CSP) settings so that the head markup works as expected.
1. Access **Experience Builder** | **Settings** | **Security**.
2. Select **Relaxed CSP: Permit Access to Inline Scripts and Allowed Hosts**, and then click **Allow** in the confirmation window.
3. Under **CSP Errors**, you see a list of blocked sites. Click **Allow URL** for each site you want to allow as Pardot tracker domains.
After enabling a successful integration between Pardot and Experience Cloud, you can accurately track page views and score leads based on a visitor’s Experience Cloud site navigation.
**See Also**
- [*Salesforce Help*: Implement Tracking Code](https://help.salesforce.com/articleView?id=mktg.pardot_implement_tracking_code.htm&type=5)
- [*Salesforce Help*: Add Markup to the Page `` to Customize Your Experience Builder Site](https://help.salesforce.com/articleView?id=experience.community_builder_page_head.htm&type=5)
- [*Salesforce Help*: Where to Allowlist Third-Party Hosts for Experience Builder Sites](https://help.salesforce.com/articleView?id=experience.networks_security_csp_allow.htm&type=5)
# Add Query Parameters
To add query parameters to the URL, update the PageReference `state` property. The key-value pairs of the `state` property are serialized to URL query parameters. The query parameters describe the page and form a more specific URL that the user can save or bookmark.
Keep these behaviors in mind when working with the `state` property.
- You can’t directly change the `pageReference` object. To update the `state`, create a new `pageReference` object, and copy the values using `Object.assign({}, pageReference)`.
- `state` parameters must be namespaced. For example, a managed package with the namespace `abc` with a parameter `accountId` is represented as `abc__accountId`. The namespace for custom components is `c__`.Parameters without a namespace are reserved for Salesforce use. This namespace restriction is introduced under a critical update in Winter ’19 and enforced in Summer ’19.
- Since the key-value pairs of `PageReference.state` are serialized to URL query parameters, all the values must be strings.
- Code that consumes values from `state` must parse the value into its proper format.
- To delete a value from the `state` object, define it as `undefined`.
If your component uses the `lightning:hasPageReference` or `lightning:isUrlAddressable` interfaces, always implement a change handler. When the target of a navigation action maps to the same component, the routing container might simply update the `pageReference` attribute value instead of recreating the component. In this scenario, a change handler ensures that your component reacts correctly.
# addClass()
Adds a CSS class to a component.
## Signature
`addClass(Object element, String newClass)`
## Parameters
**_element_:** Type: `Object`. The component to apply the class on.
**_newClass_:** Type: `String`. The CSS class to be applied.
## Sample Code
```javascript
// find a component with aura:id="myCmp" in markup
var myCmp = component.find("myCmp");
$A.util.addClass(myCmp, "myClass");
```
# addErrorHandler()
Mounts an error handling function, to be called when the messaging framework encounters an error.
## Sample
Used within a JavaScript app uploaded as a static resource and referenced by `lightning:container`, this example mounts a message error handling function. In a React app, functions must be mounted to be part of the document-object model and rendered in the output.
```javascript
componentDidMount() {
LCC.addErrorHandler(this.onMessageError);
}
```
## Arguments
| Name | Type | Description |
| -------------------------------------- | -------- | -------------------------------------------------------------------------------- |
| `handler: (errorMsg: string) => void)` | function | The function that handles error messages encountered in the messaging framework. |
## Response
None.
# addEventHandler()
Dynamically adds an event handler for a component or application event.
## Signature
`addEventHandler(String event, function handler, String phase, Boolean includeFacets)`
## Parameters
**_event_:** Type: `String`. The name of the event to handle. For a component event, set this argument to match the name attribute of the `aura:registerEvent` tag. For an application event, set this argument to match the event descriptor, `namespace:eventName`.
**_handler_:** Type: `function`. The handler for the event. There are two format options for this argument.
- To use a controller action, use the format: `cmp.getReference("c.actionName")`.
- To use an anonymous function, use the format: `function(auraEvent) { // handling logic here }`
**_phase_:** Type: `String`. Optional. The event bubbling phase for which to add the handler. The default value is `"bubble"`.
**_includeFacets_:** Type: `Boolean`. If `true`, attempts to catch events generated by components transcluded by facets; for example `v.body`.
## Sample Code
```javascript
// For component event, first param matches name attribute in tag
cmp.addEventHandler("compEvent", cmp.getReference("c.handleEvent"));
// For application event, first param is event descriptor, "c:appEvent"
cmp.addEventHandler("c:appEvent", cmp.getReference("c.handleAppEvent"));
// Anonymous function handler for component event
cmp.addEventHandler("compEvent", function(auraEvent) {
// add handler logic here
console.log("Handled the component event in anonymous function");
});
```
**See Also**
- [Dynamically Adding Event Handlers To a Component](https://developer.salesforce.com/docs/platform/aura-platform/js-cb/js-cb-dynamic-handler.md)
- [removeEventHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-removeeventhandler.md)
# addHandler()
Deprecated. Use `addEventHandler()` instead.
## Signature
`addHandler(String eventName, Object valueProvider, Object actionExpression, Boolean insert, String phase, Boolean includeFacets)`
## Parameters
**_eventName_:** Type: `String`. The name of the event to handle. For a component event, set this argument to match the name attribute of the `aura:registerEvent` tag. For an application event, set this argument to match the event descriptor, `namespace:eventName`.
**_valueProvider_:** Type: `Object`. The value provider to use for resolving the `actionExpression`.
**_actionExpression_:** Type: `Object`. The expression to use for resolving the handler action against the given `valueProvider`.
**_insert_:** Type: `Boolean`. If `true`, put the handler at the beginning instead of the end of the handler array.
**_phase_:** Type: `String`. Optional. The event bubbling phase for which to add the handler. The default value is `"bubble"`.
**_includeFacets_:** Type: `Boolean`. If `true`, attempts to catch events generated by components transcluded by facets; for example `v.body`.
**See Also**
- [addEventHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addeventhandler.md)
# Adding and Customizing Input Field Labels
When used inside of a `` component, Visualforce input components and some output components automatically display a form label for the field. For components that map to standard or custom object fields, the displayed label is the object field label by default. To override the default value, and for components that aren’t mapped directly to object fields, you can set the label using the `label` attribute of the component. For example:
```apex_page
```

**note:** For this page to display contact data, the ID of a valid contact record must be specified as a query parameter in the URL for the page. For example,
```nolang
https://MyDomain_login_URL/apex/myPage?id=003D000000Q513R
```
[Displaying Field Values with Visualforce](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-quick-start-display-field-values.md) has more information about retrieving the ID of a record.
The `label` attribute may be a string, or an expression that evaluates to a string. If you set `label` to an empty string, the form label for that field will be suppressed.
The `label` attribute can be set on the following Visualforce components:
- ``
- ``
- ``
- ``
- ``
- ``
- ``
- ``
- ``
- ``
## Custom Labels and Error Messages
When set, the `label` attribute will be used for component-level error messages, for example, when a field is required or must be unique. Custom labels won't be used in custom error messages, and the default object field label will be used instead. If you set a `label` attribute to an empty string, the default object field label will be used in all error messages.
# Adding and Removing Styles
You can add or remove a CSS style on a component or element during runtime.
To retrieve the class name on a component, use `component.find('myCmp').get('v.class')`, where `myCmp` is the `aura:id` attribute value.
To append and remove CSS classes from a component or element, use the `$A.util.addClass(cmpTarget, 'class')` and `$A.util.removeClass(cmpTarget, 'class')` methods.
## Component Source
```nolang