# 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. ![browser console stack trace](https://developer.salesforce.com/media/aura-platform/if_stack_trace.png) 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. ![browser console stack trace](https://developer.salesforce.com/media/aura-platform/iteration_stack_trace.png) 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 ``` **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: ![A simple pie chart](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_charting_simple_pie_chart.png) ```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 (![Search icon](https://developer.salesforce.com/media/salesforce-pages-developers-guide/search_apex.gif)) 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 (![Go To Line icon](https://developer.salesforce.com/media/salesforce-pages-developers-guide/go_to_line.gif)) 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 (![Undo icon](https://developer.salesforce.com/media/salesforce-pages-developers-guide/undo.gif)) to reverse an editing action and redo (![Redo icon](https://developer.salesforce.com/media/salesforce-pages-developers-guide/redo.gif)) 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 (![Go To Line icon](https://developer.salesforce.com/media/salesforce-pages-developers-guide/go_to_line.gif)) 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. ![Test expandable section](https://developer.salesforce.com/media/aura-platform/expandable_section.png) 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: ![Result of the example page.](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_controller_std_sosc_sample_1.jpg) 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. ![Events can be triggered by actions or other events.](https://developer.salesforce.com/media/aura-platform/actionsNevents.png) 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**. ![Canvas App in the Page Layout Palette](https://developer.salesforce.com/media/canvas-framework/canvas_app_page_layout.png) 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 ![Wrench icon](https://developer.salesforce.com/media/canvas-framework/wrench.jpg). - `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__chn 1000]]> 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__chn 1000]]> AccountChangeEvent ``` This `package.xml` file references the channel and channel member. ```nolang FilteredChannel__chn PlatformEventChannel FilteredChannel_chn_AccountChangeEvent PlatformEventChannelMember 68.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__chn 1000000]]> LeadChangeEvent ``` This `package.xml` file references both channel members. ```nolang FilteredChannel__chn PlatformEventChannel FilteredChannel_chn_AccountChangeEvent FilteredChannel_chn_LeadChangeEvent PlatformEventChannelMember 68.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__chn 10.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__chn 10.50]]> ns__Order_Event__e ``` This package.xml file references the channel and channel member. ```nolang MyChannel__chn PlatformEventChannel MyChannel_chn_Order_Event_e PlatformEventChannelMember 68.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. ![Query results in Developer Console.](https://developer.salesforce.com/media/caf-dev/caf_dev_geocode_post_query.png) 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
Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}
``` 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:

Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}
``` **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. ![LWC Quick Actions mobile layout](https://developer.salesforce.com/media/mobile-offline/dx_onboard_lwc_qa.png) 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 ``` ![Using the label attribute to customize form field labels.](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_input_field_labels.png) **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
Change Me!

``` ## CSS Source ```nolang .THIS.changeMe { background-color:yellow; width:200px; } ``` ## Client-side Controller Source ```javascript { applyCSS: function(cmp, event) { var cmpTarget = cmp.find('changeIt'); $A.util.addClass(cmpTarget, 'changeMe'); }, removeCSS: function(cmp, event) { var cmpTarget = cmp.find('changeIt'); $A.util.removeClass(cmpTarget, 'changeMe'); } } ``` The buttons in this demo are wired to controller actions that append or remove the CSS styles. To append a CSS style to a component, use `$A.util.addClass(cmpTarget, 'class')`. Similarly, remove the class by using `$A.util.removeClass(cmpTarget, 'class')` in your controller. `cmp.find()` locates the component using the local ID, denoted by `aura:id="changeIt"` in this demo. ## Toggling a Class To toggle a class, use `$A.util.toggleClass(cmp, 'class')`, which adds or removes the class. The `cmp` parameter can be component or a DOM element. **note:** We recommend using a component instead of a DOM element. If the utility function is not used inside `afterRender()` or `rerender()`, passing in `cmp.getElement()` might result in your class not being applied when the components are rerendered. For more information, see [Events Fired During the Rendering Lifecycle](https://developer.salesforce.com/docs/platform/aura-platform/components/components-lifecycle.md). To hide or show markup dynamically, see [Dynamically Showing or Hiding Markup](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cb-show-hide-markup.md#dynamically-showing-or-hiding-markup). To conditionally set a class for an array of components, pass in the array to `$A.util.toggleClass()`. ```javascript mapClasses: function(arr, cssClass) { for(var cmp in arr) { $A.util.toggleClass(arr[cmp], cssClass); } } ``` **See Also** - [Handling Events with Client-Side Controllers](https://developer.salesforce.com/docs/platform/aura-platform/js/js-client-side-controller.md) - [CSS in Components](https://developer.salesforce.com/docs/platform/aura-platform/components/components-css.md) - [Component Bundles](https://developer.salesforce.com/docs/platform/aura-platform/components/components-bundle.md) # Adding Aura Components to Managed Packages Add an Aura component to a managed package from a package detail page in Setup. When you add an application or component to a package, all definition bundles referenced by the application or component are automatically included, such as other components, events, and interfaces. Custom fields, custom objects, list views, page layouts, and Apex classes referenced by the application or component are also included. However, when you add a custom object to a package, you must explicitly add the application and other definition bundles that reference that custom object to the package. Other dependencies that you must add to a package explicitly include the following. - Trusted URLs - Remote Site Settings **See Also** - [Second-Generation Managed Packaging Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.pkg2_dev.meta/pkg2_dev/sfdx_dev_dev2gp.htm) - [First-Generation Managed Packaging Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.pkg1_dev.meta/pkg1_dev/sharing_apps.htm) # Adding Custom List Buttons using Standard List Controllers In addition to overriding standard buttons and links, you can also create custom list buttons that link to pages that use a standard list controller. These list buttons can be used on a list page, search results, and any related list for the object and allow you to take actions on a group of selected records. To indicate the set of records that have been selected, use the `{!selected}` expression. For example, to add a custom button to a related list for opportunities that allows you to edit and save the opportunity stage and close date on selected records: 1. Create the following Apex class: ```apex public class tenPageSizeExt { public tenPageSizeExt(ApexPages.StandardSetController controller) { controller.setPageSize(10); } } ``` 2. Create the following page and call it `oppEditStageAndCloseDate`: ```visualforce ``` 3. Make the page available to all users. 1. From Setup, enter `Visualforce Pages` in the `Quick Find` box, then select **Visualforce Pages**. 2. Click **Security** for the oppEditStageAndCloseDate page. 3. Add the appropriate profiles to the `Enabled Profiles` list. 4. Click **Save**. 4. Create a custom button on opportunities. 1. From the object management settings for opportunities, go to Buttons, Links, and Actions. 2. Click the button for creating a new button or link. 3. Set the `Label` to `Edit Stage & Date`. 4. Set the `Display Type` to `List Button`. 5. Set the Content Source to `Visualforce Page`. 6. From the Content drop-down list, select `oppEditStageAndCloseDate`. 7. Click **Save**. 8. A warning will display notifying you that the button will not be displayed until you have updated page layouts. Click **OK**. 5. Add the custom button to an account page layout. 1. From the object management settings for accounts, go to Page Layouts. 2. Click **Edit** for the appropriate page layout. 3. In the **Related List Section**, click on **Opportunities**, then click ![Editable Field](https://developer.salesforce.com/media/salesforce-pages-developers-guide/wrench.gif) to edit the properties. 4. In the Custom Buttons section, select **Edit Stage & Date** in the Available Buttons list and add it to the Selected Buttons list. 5. Click **OK**. 6. Click **Save**. Now, when you visit the account page, there is a new button in the opportunities related list. ![An Opportunities related list with an Edit Stage and Date button](https://developer.salesforce.com/media/salesforce-pages-developers-guide/custom_rel_list_button.png "Example of New Button") When you select an opportunity and click **Edit Stage & Date**, you are taken to your custom edit page. ![The Edit Stage and Date page](https://developer.salesforce.com/media/salesforce-pages-developers-guide/custom_sosc_edit_page.png "Example of Custom Edit Page") **See Also** - [*Salesforce Help*: Find Object Management Settings](https://help.salesforce.com/HTViewHelpDoc?id=extend_click_find_objectmgmt_parent.htm) # Adding Dependent Fields to a Page Dependent fields provide a way to filter the field values displayed on a Visualforce page. Dependent fields consist of two parts: a controlling field that determines the filtering, and a dependent field that has its values filtered. Dependent fields can dynamically filter values in fields such as picklists, multi-select picklists, radio buttons, and checkboxes. Dependent picklists can only be displayed on Visualforce pages with Salesforce API version 19.0 or higher. For this example, we’ll be adding a dependent picklist, Subcategories, to a Visualforce page. First, create this custom picklist: 1. From the object management settings for accounts, go to the fields area, and then click **New**. 2. Choose **Picklist**, and then click **Next**. 3. Enter `Subcategories` for the **Field Label**. 4. Enter the following terms for the list of values: - Apple Farms - Cable - Corn Fields - Internet - Radio - Television - Winery 5. Click **Next** twice, then click **Save**. To define the field dependencies for Subcategories: 1. From the object management settings for accounts, go to the fields area. 2. Click **Field Dependencies**. 3. Click **New**. 4. Choose Industry as a controlling field, and Subcategories as a dependent field. 5. Click **Continue**. 6. Each value in the controlling field (from Industry) is listed in the top row and each value in the dependent field (from Subcategory) is displayed in the column below it. Set your field dependencies to match this image: ![The field dependency matrix for Subcategories](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_quick_start_field_dependency_matrix.png "The Field Dependency Matrix for Subcategories") You can disregard any other Industry types that aren’t shown above. 7. Click **Save**. Now, create a Visualforce page called `dependentPicklists` that looks like this: ```visualforce ``` When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you select Communication, your Subcategories picklist contains all the Communication types defined earlier. ## Dependent Picklist Considerations Consider the following when using dependent picklists in Visualforce pages: - You can mix controlling and dependent fields across various field types, such as picklists, multi-picklists, radio buttons, and checkboxes. - There’s a limit of 10 dependent picklist pairs per page. This is totalled across all objects. Thus, you could have five dependent picklists on Account, and five on Contact, but no more. However, you can repeat the same pair of dependent picklists, such as in an iterative tag like ``, without counting more than once against your limit. - Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime error when the page displays. **note:** If the API version used is 26.0 or earlier, and the user viewing the page has **read-only** access to the controlling field, the dependent picklist shows all possible values for the picklist, instead of being filtered on the read-only value. This is a known limitation in Visualforce. - Don’t mix inline edit-enabled fields with regular input fields from the same dependency group. For example, don’t mix a standard input field for a controlling field with an inline edit-enabled dependent field: ```visualforce ``` - If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or controlling relationships to each other as one group. Refreshing fields individually isn’t recommended and might result in inconsistent undo/redo behavior. Here’s an example of the recommended way to partially refresh a form with inline edit-enabled dependent picklists: ```visualforce ``` All of the inline edit-enabled picklists are wrapped in the `` component. The `` rerenders when the `` action method fires. **See Also** - [*Salesforce Help*: Find Object Management Settings](https://help.salesforce.com/HTViewHelpDoc?id=extend_click_find_objectmgmt_parent.htm) # Adding Info Windows to Markers Info windows allow you to show extra details on a map. Info windows appear when a user clicks or taps the marker. The map marker `title` attribute lets you display a small amount of information when a user hovers over the marker. To display more information or have more control over how it’s formatted, use an info window instead of or in addition to the `title` attribute. For example, you can display complete details for a contact’s address, formatted for optimal display. You can add a clickable telephone link or even display a profile photo for objects that have one. To add an info window to a map marker, add an `` component as a child component of the associated ``. The body of the `` component is displayed in the info window when users click or tap the marker, and can be Visualforce markup, HTML and CSS, or plain text. This complete page uses Visualforce markup for the contents of the info window. ```visualforce {! ct.Name } {! ct.MailingStreet } {! ct.MailingCity }, {! ct.MailingState } {! ct.Phone } ``` This code produces the following map. ![A map with markers displaying an info window](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_maps_info_window.png) By default, only one info window displays at a time. When you click another marker, the first info window closes, and the new info window opens. To display multiple info windows at once, set `showOnlyActiveInfoWindow` to `false` on the containing `` component. **note:** Consider carefully the effect of displaying multiple info windows at once, because it can create a cluttered map. # Adding JavaScript Remoting to a Visualforce Page To use JavaScript remoting in a Visualforce page, add the request as a JavaScript function call. Add the Apex class as a custom controller or a controller extension to your page. ```apex ``` **warning:** Adding a controller or controller extension grants access to all `@RemoteAction` methods in that Apex class, even if those methods aren’t used in the page. Anyone who can view the page can execute all `@RemoteAction` methods and provide fake or malicious data to the controller. Then, add the request as a JavaScript function call. A simple JavaScript remoting invocation takes the following form. ```javascript [namespace.]MyController.method( [parameters...,] callbackFunction, [configuration] ); ``` | Element | Description | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `namespace` | The namespace of the controller class. The namespace element is required if your organization has a namespace defined, or if the class comes from an installed package. | | `MyController`, `MyExtension` | The name of your Apex controller or extension. | | `method` | The name of the Apex method you’re calling. | | `parameters` | A comma-separated list of parameters that your method takes. | | `callbackFunction` | The name of the JavaScript function that handles the response from the controller. You can also declare an anonymous function inline. `callbackFunction` receives the status of the method call and the result as parameters. | | `configuration` | Configures the handling of the remote call and response. Use this element to change the behavior of a remoting call, such as whether or not to escape the Apex method’s response. | The remote method call executes synchronously, but it doesn’t wait for the response to return. When the response returns, the callback function handles it asynchronously. See [Handling the Remote Response](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-js-remoting-handling-response.md#handling-the-remote-response) for details. # Adding Location Markers to a Map You can add markers to a map to represent specific locations using the `` component. You can include text that displays when a pointer hovers over the marker. To place a marker on a map, add an `` component as a child of the associated ``. You specify the marker’s location with the `position` attribute. Optionally, use the `title` attribute to display text when the pointer hovers over the marker. You can add up to 100 markers to a map. Use an `` iteration component to add multiple markers from a collection or list. **note:** Visualforce maps can be resource-intensive which can cause memory issues within mobile browsers and the Salesforce app. Maps with many markers or large images used as custom markers can further increase memory consumption. If you plan to deploy Visualforce maps in pages that are used in mobile contexts, be sure to test those pages thoroughly. The `position` attribute defines the point on the map to place the marker. You can provide `position` values in several formats. **note:** You can have up to 10 geocoded address lookups per map. Lookups for both the `center` attribute of the `` component and the `position` attribute of the `` component count against this limit. To display more markers, provide `position` values that don’t require geocoding. Locations that exceed the geocoding limit are skipped. - A string that represents an address. For example, "1 Market Street, San Francisco, CA". The address is geocoded to determine its latitude and longitude. - A string that represents a JSON object with `latitude` and `longitude` attributes that specify location coordinates. For example, "{latitude: 37.794, longitude: -122.395}". - An Apex map object of type `Map`, with `latitude` and `longitude` keys to specify location coordinates. Here’s a page that shows a list of contacts for an account, centered on the account’s address. ```markup ``` This code produces the following map. ![A map with markers](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_maps_markers.png) Notice the following in this example. - The `center` and `position` attributes are passed as a Visualforce expression that concatenates address elements to provide an address string that can be geocoded. - Because this page uses geocoding for the addresses, it displays only the first nine contacts. The `center` attribute of `` uses one geocoding lookup as part of the 10 allowed. (In the illustration, the account has only three contacts.) # Adding Visualforce to a Salesforce AppExchange App You can include Visualforce pages, components, or custom controllers in an app that you are creating for AppExchange. Unlike Apex classes, the content of a Visualforce page in a managed package is not hidden when the package is installed. However, custom controllers, controller extensions, and custom components are hidden. In addition, custom components can be restricted with the `access` attribute to run only in your namespace. Salesforce recommends that you only use managed packages to distribute any Visualforce or Apex components. This recommendation is because managed packages receive a unique namespace that is automatically prepended to the names of your pages, components, classes, methods, variables, and so on. This namespace prefix helps prevent duplicate names in the installer's organization. Consider the following caveats when you create a package using a Visualforce page: - If the `access` attribute on a component that is included in a managed package is set to `global`, be aware of the following restrictions: - The `access` attribute on the component cannot be changed to `public`. - All required child `` components (those that have the required attribute set to true) must have the `access` attribute set to global. - If the `default` attribute is set on a required child ``, it cannot be removed or changed. - You cannot add new required child `` components. - If the `access` attribute on a child `` component is set to `global`, it cannot be changed to `public`. - If the `access` attribute on a child `` component is set to `global`, the `type` attribute cannot be changed. - When a package with a non-global component is installed, users that view the component in Setup see “Component is not global” instead of the content of the component. In addition, the component is not included in the component reference. - If advanced currency management is enabled for an organization that is installing a package, Visualforce pages that use `` and `` cannot be installed. - Any Apex that is included as part of an AppExchange app must have at least 75% cumulative test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors. The tests are also run when the package is installed. - Beginning with version 16.0, if you have a managed `global` Apex class used as a Visualforce controller, it is also required that the access level be set to `global` for the following methods and properties for subscribers to use them: - Constructors for custom controllers - Getter and setter methods, including those for input and output components - Get and set attributes on properties **tip:** If a custom label has translations, include the translations in a package by explicitly packaging the desired languages. To prevent malicious code in a package from affecting your data, when a package containing Visualforce pages is installed into an organization, the pages are served from the vf.force.com, domain instead of the salesforce.com domain. **See Also** - [Test a Custom Controller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/controller/pages-controller-error-handling.md) - [*Second-Generation Managed Packaging Developer Guide*: Create a Second-Generation Managed Package](https://developer.salesforce.com/docs/atlas.en-us.pkg2_dev.meta/pkg2_dev/sfdx_dev_dev_2gp_developing_2gp_packages.htm) # Additional Considerations for Apex in an Offline-Enabled Mobile App The following differences in behavior compared to Apex run from a browser-based connection apply to Apex when used in Lightning web components in an offline-enabled mobile app. If a quick action uses a wired Apex method, and that quick action is primed at app startup, then the Apex results data can be primed as well, and available offline. The LWC must be statically analyzable for priming to take place. Specifically, input parameters for the wire adapter must be analyzable. For example, if the input parameters are derived from page reference attributes, or from the output of another LDS wire that is also analyzable. See [Validate Lightning Web Components for Offline Use](https://developer.salesforce.com/docs/platform/mobile-offline/dx/dx-validate-lwc-offline.md) for additional details about static analysis. Note that the Apex method will be invoked during priming, possibly many times, to prime results for all possible adapter input parameters. Apex continuations are supported. However, because continuations tend to be longer running requests, we recommend providing feedback to the user while a continuation is active. Otherwise, they might go offline before a continuation completes, which results in an error. # Additional Documentation for Apex in Lightning Web Components Learn more about how to use Apex, including continuations, from Lightning web components documentation resources. In addition to the [Call Apex Methods](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex) chapter, see the `@salesforce/apex` and `@salesforce/apexContinuations` sections of the [`@salesforce` Modules reference](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_salesforce_modules) in the _Lightning Web Components Developer Guide_. # AdditionalInformationMap Represents other information, if any, about matched records. ## Fields ### `name` **Type:** string **Description:** The name of the element. ### `value` **Type:** string **Description:** The value of the element. # addMessageHandler() Mounts a message handling function, used to handle messages sent from the Aura component to the framed JavaScript app. ## Sample Used within a JavaScript app uploaded as a static resource and referenced by `lightning:container`, this example mounts a message 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.addMessageHandler(this.onMessage); } onMessage(msg) { let name = msg.name; if (name === "General") { let value = msg.value; this.setState({messageReceived: value}); } else if (name === "Foo") { // A different response } } ``` ## Arguments | Name | Type | Description | | --------------------------------- | -------- | ---------------------------------------------------------------- | | `handler: (userMsg: any) => void` | function | The function that handles messages sent from the Aura component. | ## Response None. # addValueHandler() Adds handlers to values owned by the component. ## Signature `addValueHandler(Object config)` ## Parameters **_config_:** Type: `Object`. The value event, such as `"change"`, and the action, such as `"c.myAction"`. # addValueProvider() Adds custom value providers to a component. ## Signature `addValueProvider(String key, Object valueProvider)` ## Parameters **_key_:** Type: `String`. Key to identify the value provider. Used in expressions in markup. **_valueProvider_:** Type: `Object`. The object to request data from. Must implement `get(expression)`, can implement `set(key,value)`. **See Also** - [Value Providers](https://developer.salesforce.com/docs/platform/aura-platform/expr/expr-source.md) # Advanced Events Example This example builds on the simpler component and application event examples. It uses one notifier component and one handler component that work with both component and application events. Before we see a component wired up to events, let's look at the individual resources involved. This table summarizes the roles of the various resources used in the example. The source code for these resources is included after the table. | Resource | Resource Name | Usage | | ------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Event files | Component event (`compEvent.evt`) and application event (`appEvent.evt`) | Defines the component and application events in separate resources. `eventsContainer.cmp` shows how to use both component and application events. | | Notifier | Component (`eventsNotifier.cmp`) and its controller (eventsNotifierController.js) | The notifier contains an `onclick` browser event to initiate the event. The controller fires the event. | | Handler | Component (`eventsHandler.cmp`) and its controller (eventsHandlerController.js) | The handler component contains the notifier component (or a `` tag for application events), and calls the controller action that is executed after the event is fired. | | Container Component | `eventsContainer.cmp` | Displays the event handlers on the UI for the complete demo. | The definitions of component and application events are stored in separate `.evt` resources, but individual notifier and handler component bundles can contain code to work with both types of events. The component and application events both contain a `context` attribute that defines the shape of the event. This is the data that is passed to handlers of the event. ## Component Event Here is the markup for `compEvent.evt`. ```nolang ``` ## Application Event Here is the markup for `appEvent.evt`. ```nolang ``` ## Notifier Component The `eventsNotifier.cmp` notifier component contains buttons to initiate a component or application event. The notifier uses `aura:registerEvent` tags to declare that it may fire the component and application events. Note that the `name` attribute is required, but the value is only relevant for the component event; the value is not used anywhere else for the application event. The `parentName` attribute is not set yet. We will see how this attribute is set and surfaced in `eventsContainer.cmp`. ```nolang

This is {!v.parentName}'s eventsNotifier.cmp instance

``` ### CSS Source The CSS is in `eventsNotifier.css`. ```nolang /* eventsNotifier.css */ .cEventsNotifier { display: block; margin: 10px; padding: 10px; border: 1px solid black; } ``` ### Client-side Controller Source The `eventsNotifierController.js` controller fires the event. ```javascript /* eventsNotifierController.js */ { fireComponentEvent : function(cmp, event) { var parentName = cmp.get("v.parentName"); // Look up event by name, not by type var compEvents = cmp.getEvent("componentEventFired"); compEvents.setParams({ "context" : parentName }); compEvents.fire(); }, fireApplicationEvent : function(cmp, event) { var parentName = cmp.get("v.parentName"); // note different syntax for getting application event var appEvent = $A.get("e.c:appEvent"); appEvent.setParams({ "context" : parentName }); appEvent.fire(); } } ``` You can click the buttons to fire component and application events, but there is no change to the output because we haven't wired up the handler component to react to the events yet. The controller sets the `context` attribute of the component or application event to the `parentName` of the notifier component before firing the event. We will see how this affects the output when we look at the handler component. ## Handler Component The `eventsHandler.cmp` handler component contains the `c:eventsNotifier` notifier component and `` tags for the application and component events. ```nolang

This is {!v.name}

{!v.mostRecentEvent}

# component events handled: {!v.numComponentEventsHandled}

# application events handled: {!v.numApplicationEventsHandled}

``` **note:** `{#v.name}` is an unbound expression. This means that any change to the value of the `parentName` attribute in `c:eventsNotifier` doesn’t propagate back to affect the value of the `name` attribute in `c:eventsHandler`. For more information, see [Data Binding Between Components](https://developer.salesforce.com/docs/platform/aura-platform/expr/expr-data-binding.md#data-binding-between-components). ### CSS Source The CSS is in `eventsHandler.css`. ```nolang /* eventsHandler.css */ .cEventsHandler { display: block; margin: 10px; padding: 10px; border: 1px solid black; } ``` ### Client-side Controller Source The client-side controller is in `eventsHandlerController.js`. ```javascript /* eventsHandlerController.js */ { handleComponentEventFired : function(cmp, event) { var context = event.getParam("context"); cmp.set("v.mostRecentEvent", "Most recent event handled: COMPONENT event, from " + context); var numComponentEventsHandled = parseInt(cmp.get("v.numComponentEventsHandled")) + 1; cmp.set("v.numComponentEventsHandled", numComponentEventsHandled); }, handleApplicationEventFired : function(cmp, event) { var context = event.getParam("context"); cmp.set("v.mostRecentEvent", "Most recent event handled: APPLICATION event, from " + context); var numApplicationEventsHandled = parseInt(cmp.get("v.numApplicationEventsHandled")) + 1; cmp.set("v.numApplicationEventsHandled", numApplicationEventsHandled); } } ``` The `name` attribute is not set yet. We will see how this attribute is set and surfaced in `eventsContainer.cmp`. You can click buttons and the UI now changes to indicate the type of event. The click count increments to indicate whether it's a component or application event. We aren't finished yet though. Notice that the source of the event is undefined as the event `context` attribute hasn't been set . ## Container Component Here is the markup for `eventsContainer.cmp`. ```nolang ``` The container component contains two handler components. It sets the `name` attribute of both handler components, which is passed through to set the `parentName` attribute of the notifier components. This fills in the gaps in the UI text that we saw when we looked at the notifier or handler components directly. Add the `c:eventsContainer` component to a `c:eventsContainerApp` application. Navigate to the application. `https://MY_DOMAIN_NAME.lightning.force.com/c/eventsContainerApp.app`. Click the **Click here to fire a component event** button for either of the event handlers. Notice that the **# component events handled** counter only increments for that component because only the firing component's handler is notified. Click the **Click here to fire an application event** button for either of the event handlers. Notice that the **# application events handled** counter increments for both the components this time because all the handling components are notified. **See Also** - [Component Event Example](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-component-example.md) - [Application Event Example](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-application-example.md) - [Event Handling Lifecycle](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-overview.md) # Advanced Examples The examples in [the quick start tutorial](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/pages-quick-start.md) are considered beginning examples, and primarily use only Visualforce markup. Advanced examples use Lightning Platform Apex code in addition to Visualforce markup. # Advanced Topics This chapter contains information about advanced activities in the AJAX Toolkit. - **[QueryResultIterator](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-queryresultiterator.md)** Iterate over query results returned by the AJAX Toolkit without invoking `queryMore` and `queryLocator`. - **[Differences in Escaping Reserved Characters](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-escape-char.md)** If you have a single quote or backslash in a string literal, use two backslashes instead of one to escape it. - **[Working with Base64 Binary Encoded Strings](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-base64issue.md)** When working with Base64 encoded binary documents, access the document directly using the Id, rather than decoding Base64 in JavaScript. - **[Timeout Parameter for Asynchronous Calls](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-timeout.md)** If an asynchronous call does not complete in an appropriate amount of time, you can end the call. To do this, specify the `timeout` parameter in the callback section of any asynchronous call. - **[AJAX Proxy](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-proxy.md)** Some browsers don't allow JavaScript code to connect to external servers directly. Therefore, you may need to send requests through the AJAX proxy. # AgentQltyEvalEvent Notifies subscribers of quality evaluations for agents that occur during voice calls, messaging sessions, and case interactions. This object is available in API version 68.0 and later. ## Supported Calls `describeSObjects()` ## Special Access Rules To access this object, you must be assigned QualityManagementEnabled org perm. ## Fields ### `AgentId` **Type:** reference **Description:** User ID of the agent quality evaluation event. This field is a relationship field. **Relationship Name:** Agent **Refers To:** User ### `AssessmentId` **Type:** reference **Description:** Assessment ID of the quality evaluation event for the agent. This field is a relationship field. **Relationship Name:** Assessment **Refers To:** Assessment ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies the agent quality evaluation event. ### `InteractionId` **Type:** reference **Properties:** Nillable **Description:** Interaction ID of the agent quality evaluation event. This field is a polymorphic relationship field. **Relationship Name:** Interaction **Refers To:** Case, MessagingSession, VoiceCall ### `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. ### `Type` **Type:** picklist **Properties:** Restricted picklist **Description:** Type of the Platform event that triggered the quality evaluation for the agent. # Aggregate Functions Use aggregate functions in a `GROUP BY` clause in SOQL queries to generate reports for analysis. Aggregate functions include `AVG()`, `COUNT()`, `MIN()`, `MAX()`, `SUM()`, and more. You can also use aggregate functions _without_ using a `GROUP BY` clause. For example, you could use the `AVG()` aggregate function to find the average `Amount` for all your opportunities. ```soql SELECT AVG(Amount) FROM Opportunity ``` However, these functions become a more powerful tool to generate reports when you use them with a `GROUP BY` clause. For example, you could find the average `Amount` for all your opportunities by campaign. ```soql SELECT CampaignId, AVG(Amount) FROM Opportunity GROUP BY CampaignId ``` This table lists all the aggregate functions supported by SOQL. **note:** All aggregate functions ignore null values, except for `COUNT()` and `COUNT(Id)`. `COUNT(fieldname)` is different from `COUNT()`. `COUNT(fieldname)` does ignore null values. | Aggregate Function | Description | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `AVG()` | Returns the average value of a numeric field. | | `COUNT()` and `COUNT(fieldName)` | Returns the number of rows matching the query criteria. | | `COUNT_DISTINCT()` | Returns the number of distinct non-`null` field values matching the query criteria. | | `MIN()` | Returns the minimum value of a field. If you use the `MIN()` or `MAX()` functions on a picklist field, the function uses the sort order of the picklist values instead of alphabetical order. | | `MAX()` | Returns the maximum value of a field. Available in API version 18.0 and later. | | `SUM()` | Returns the total sum of a numeric field. | Example `AVG()`: ```soql SELECT CampaignId, AVG(Amount) FROM Opportunity GROUP BY CampaignId ``` Example using `COUNT()`: ```codesegment SELECT COUNT() FROM Account WHERE Name LIKE 'a%' ``` Example using `COUNT(fieldName)`: ```codesegment SELECT COUNT(Id) FROM Account WHERE Name LIKE 'a%' ``` **Note:** `COUNT()` and `COUNT(Id)` in SOQL are similar to `COUNT(*)` in SQL. Example `COUNT_DISTINCT()`: ```soql SELECT COUNT_DISTINCT(Company) FROM Lead ``` **Note:** `COUNT_DISTINCT(fieldName)` in SOQL is equivalent to `COUNT(DISTINCT fieldName)` in SQL. . Example `MIN()`: ```soql SELECT MIN(CreatedDate), FirstName, LastName FROM Contact GROUP BY FirstName, LastName ``` Example `MAX()`: ```soql SELECT Name, MAX(BudgetedCost) FROM Campaign GROUP BY Name ``` Example `SUM()`: ```soql SELECT SUM(Amount) FROM Opportunity WHERE IsClosed = false AND Probability > 60 ``` You can't use a `LIMIT` clause in a query that uses an aggregate function, but does not use a `GROUP BY` clause. For example, the following query is invalid: ```soql SELECT MAX(CreatedDate) FROM Account LIMIT 1 ``` # AggregateResult A read-only SObject that returns query results only if a query call contains an aggregate function, such as `MAX()`. Results are returned in AggregateResult only if a `query()` or `queryMore()` call includes the aggregate function. If the call doesn't contain an aggregate function, the results are returned in the [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) SObject. For example, this query returns an array of Contact records in the `records` field. ```soql SELECT Id, LastName FROM Contact WHERE FirstName = 'Bob' ``` When a SOQL query contains an [aggregate function](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm), the record field returns an array of AggregateResult records. . ## Fields Each AggregateResult object contains a separate field for each item in the `SELECT` list. For the Enterprise WSDL, retrieve the result for each item by calling `getField()` on an AggregateResult object when using WSC client framework. For the Partner WSDL, retrieve the result for each item by calling `getField()` on an object. ## Sample Code—Java ```codesegment public void queryAggregateResult() { try { String groupByQuery = "SELECT Account.Name n, " + "MAX(Amount) max, MIN(Amount) min " + "FROM Opportunity GROUP BY Account.Name"; QueryResult qr = connection.query(groupByQuery); if (qr.getSize() > 0) { System.out.println("Query returned " + qr.getRecords().length + " results." ); for (SObject sObj : qr.getRecords()) { AggregateResult result = (AggregateResult) sObj; System.out.println("aggResult.Account.Name: " + result.getField("n") ); System.out.println("aggResult.max: " + result.getField("max") ); System.out.println("aggResult.min: " + result.getField("min") ); System.out.println(); } } else { System.out.println("No results found."); } System.out.println("\nQuery successfully executed."); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# ```codesegment private void testAggregateResult() { try { QueryResult qr = null; binding.QueryOptionsValue = new QueryOptions(); String soqlStr = "SELECT Name, " + "MAX(Amount), " + "MIN(Amount) " + "FROM Opportunity " + "GROUP BY Name"; qr = binding.query(soqlStr); if (qr.size > 0) { for (int i = 0; i < qr.records.Length; i++) { sforce.AggregateResult ar = (AggregateResult)qr.records[i]; foreach (XmlElement e in ar.Any) Console.WriteLine( "{0} - {1}", e.LocalName, e.InnerText ); } } else { Console.WriteLine("No records found"); } Console.WriteLine("Query successfully executed."); } catch (Exception ex) { Console.WriteLine( "\nFailed to execute query successfully." + "error message was: \n" + ex.Message ); } } ``` # AiJobRunStatusEvent Notifies subscribers when an `AiJobRun` object changes status to `InProgress`, `Completed`, or `Failed`. This object is available in API version 65.0 and later. ## Supported Calls `create()`, `describeSObjects()` ## Special Access Rules This object is available to users with access to the [`AiJobRun`](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_aijobrun.htm) and [`AiJobRunItem`](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_aijobrunitem.htm) standard objects. ## Fields ### `AiJobRunIdentifier` **Type:** string **Properties:** Create **Description:** The ID of the `AiJobRun` associated with this event. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `JobType` **Type:** picklist **Properties:** Create, Restricted picklist **Description:** The method used to create the job run. Possible values are `GeneratePromptAsyncIA` (Flow), or `PromptTemplate` (Apex). ### `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. ### `Status` **Type:** picklist **Properties:** Create, Restricted picklist **Description:** The `AiJobRunStatus` that the job run changed to. Possible values are `InProgress`, `Completed`, or `Failed`. ### `Target` **Type:** string **Properties:** Create, Nillable **Description:** Represents the `Target` field in `AiJobRun`. A metadata field used to specify job-specific details, such as a `PromptTemplateId`, `PromptTemplateName`, or `ModelId`. # AIPredictionEvent Notifies subscribers when an Einstein feature, such as Prediction Builder or Case Classification, has written prediction results back to a target object and AI prediction field. This object is available in API version 46.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/AIPredictionEvent` ## Special Access Rules Users with Customize Application permission have read access. ## Event Delivery Allocation Enforced No **See Also** - [*Object Reference for Salesforce and Lightning Platform* : AIRecordInsight](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_airecordinsight.htm) ## Fields ### `Confidence` **Type:** double **Properties:** Nillable **Description:** Relative confidence strength of the generated prediction result. Higher values (near 1.0) indicate stronger confidence. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `FieldName` **Type:** string **Properties:** Nillable **Description:** API name of the AI prediction field that prediction results were written back to. An AI prediction field is a custom field created for storing and displaying the prediction scores on records. The name is specified in `ObjectName.FieldName` format, for example, `Lead.predicted_score__c`. For Case Classification prediction results, this field can be null. ### `HasError` **Type:** boolean **Properties:** Defaulted on create **Description:** `true` if there was an error while gathering information to create an event message, `false` otherwise. ### `InsightId` **Type:** string **Properties:** Nillable **Description:** The unique ID of the created AIRecordInsight record that generated the event message. ### `PredictionEntityId` **Type:** string **Properties:** Nillable **Description:** The unique ID of the created AIInsightValue record associated with the AIRecordInsight that generated the 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. ### `TargetId` **Type:** string **Properties:** Nillable **Description:** The unique ID of the record Einstein is writing prediction results to. ## Usage When Einstein writes prediction results back to AI prediction fields, record save custom logic, such as Apex triggers, workflow rules, and assignment rules, aren’t run for efficiency reasons. To add custom logic based on Einstein prediction results, subscribe to AIPredictionEvent for notifications of prediction result updates. Every time prediction results are written back to a Salesforce record, an AIPredictionEvent event is created and AIPredictionEvent subscribers are notified. # AIUpdateRecordEvent Notifies subscribers when Einstein Case Classification has generated a case field value prediction and potentially updated a case record. This object is available in API version 47.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/AIUpdateRecordEvent` ## Event Delivery Allocation Enforced Yes ## Fields ### `ErrorCode` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** Indicates whether an error occurred in the automatic case update, and describes the nature of the error. Values are: - `none`—No error occurred. - `entity_locked`—The case is locked for editing by an approval process. - `no_access`—The selected Einstein user or automatic process user doesn’t have permission to make the update. For example, the user needs permission to update cases or the case field in question, or needs sharing-based access to the case. - `validation_rule`—The update violates a case validation rule. - `other`—A different error occurred. Available in API version 50.0 and later. ### `ErrorMessage` **Type:** string **Properties:** Nillable **Description:** Further describes an error that occurred in the automatic case update. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `IsUpdated` **Type:** boolean **Properties:** Defaulted on create **Description:** Indicates whether the related case (`RecordId`) was updated by Einstein Case Classification. If a case value prediction falls below the required confidence level selected in the predictive model, the case is not updated (`false`). If the prediction meets the confidence level requirement, the case field is updated and the case is saved (`true`). It is only updated if at least one field has a confidence threshold defined for the field’s Automate Value. Available in API version 49.0 and later. ### `RecordId` **Type:** string **Properties:** None **Description:** The record in which the prediction results are written. ### `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. ### `UpdatedFields` **Type:** complexvalue **Properties:** Nillable **Description:** Indicates which record fields, if any, were updated in the event.Available in API version 49.0 and later. ## Usage When Einstein Case Classification generates a case field value prediction, an AIUpdateRecordEvent event message is generated on case create whether or not Einstein updates the case, and if at least one of the prediction fields has a confidence threshold set in the Automate Value setting. A prediction will not result in a case update if its confidence level falls below the confidence threshold defined for the field’s Automate Value setting. Subscribe to AIUpdateRecordEvent to be notified of such changes and to rerun case routing logic. If all fields have a prediction that meets the confidence threshold criteria and an unexpected error prevents recommendations from being auto-applied, an AIUpdateRecordEvent is published with a corresponding ErrorCode and Error Message. If a case doesn't match the data segment filters for any of the apps, we don't score and auto-apply recommendations or publish any events. There are additional considerations to auto-apply recommendations with dependent picklists. [Learn More](https://help.salesforce.com/s/articleView?language=en_US&type=5&id=sf.cc_service_field_considerations.htm) # AJAX Proxy Some browsers don't allow JavaScript code to connect to external servers directly. Therefore, you may need to send requests through the AJAX proxy. **note:** To use the AJAX proxy, you must register all external services in the Salesforce user interface. From Setup, enter `Remote Site Settings` in the `Quick Find` box, then select **Remote Site Settings**. For security reasons, Salesforce restricts the outbound ports you may specify to one of the following: - 80: This port only accepts HTTP connections. - 443: This port only accepts HTTPS connections. - 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections. The AJAX proxy is part of the AJAX Toolkit. Access it using `remoteFunction` defined in `connection.js`. You can specify any HTTP method in `remoteFunction`, for example HTTP GET or POST, and it will be forwarded to the external service. The following examples illustrate typical approaches for GET and POST: GET Example: ```javascript sforce.connection.remoteFunction({ url : "http://www.myExternalServer.com", onSuccess : function(response) { alert("result" + response); } }); ``` POST Example: ```javascript var envelope = ""; //request envelope, empty for this example sforce.connection.remoteFunction({ url : "http://services.xmethods.net:80/soap", requestHeaders: {"Content-Type":"text/xml", "SOAPAction": "\"\"" }, requestData: envelope, method: "POST", onSuccess : function(response) { sforce.debug.log(response); }, onFailure : function(response) { alert("Failed" + response) } }); ``` - **[remote Function Syntax and Parameters](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-remotefunction-syntax.md)** AJAX proxy uses `remoteFunction` to proxy calls. - **[Download the Salesforce Client Certificate](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-client-cert-for-om.md)** Your application (endpoint) server’s SSL/TLS can be configured to require client certificates (two-way SSL/TLS) to validate the identity of the Salesforce server when it takes the role of client to your server. If so, you can download the Salesforce client certificate from the Salesforce API page. # AJAX Toolkit Developer Guide Embed API calls in Visualforce pages, buttons, and links with AJAX Toolkit — a JavaScript wrapper around SOAP API. The AJAX Toolkit supports Microsoft® Internet Explorer® versions 9, 10, and 11 with the latest Microsoft hot fixes applied, and Mozilla® Firefox®, most recent stable version. The AJAX Toolkit is based on the partner WSDL. Because there’s no type checking in JavaScript, the type information available in the enterprise WSDL isn’t needed. **note:** Before you use the AJAX Toolkit, familiarize yourself with JavaScript and with the information about SOAP API in the [SOAP API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/). - **[When to Use the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-when-to-use.md)** For best performance, use the AJAX Toolkit when working with small amounts of data. - **[Working with the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-working.md)** - **[API Calls and the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-calls.md)** This toolkit supports all SOAP API calls, as well as `runTests()` from Apex. - **[SOAP (AJAX) API End-of-Life Policy](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-eol.md)** See which SOAP API versions are supported, unsupported, or unavailable. - **[SOAP Header Options with the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-headers.md)** All header options in the SOAP API are supported in the toolkit, but they are specified differently than in the API. - **[Error Handling with the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-errors.md)** The AJAX Toolkit provides the ability to handle errors for synchronous and asynchronous calls. - **[Advanced Topics](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-advanced.md)** # AJAX Toolkit 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/apex_ajax.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/apex_ajax.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/apex_ajax.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/apex_ajax.pdf) | # AJAX Toolkit Support Policy The current release of the AJAX Toolkit is the only version that receives bug fixes and enhancements. When a new version is released, the previous version continues to be available, but is not supported. # AJAX Typographical Conventions Topics about the AJAX Toolkit use the following typographical conventions: |Convention|Description| |----------|-----------| |``|In an example, Courier font indicates items that you should type the information as shown. This includes sample code, literals, methods, calls, functions, and events from a variety of languages.| |`sforce.connection.header_option_name="value";`|In an example or syntax statement, italics represent variables. You supply the actual value.| # Alias Notation You can use alias notation in SELECT queries. ```codesegment SELECT count() FROM Contact c, c.Account a WHERE a.name = 'MyriadPubs' ``` To establish the alias, first identify the object, in this example a contact, and then specify the alias, in this case “c.” For the rest of the SELECT statement, you can use the alias in place of the object or field name. The following are SOQL keywords that can’t be used as alias names: `AND, ASC, DESC, EXCLUDES, FIRST, FROM, GROUP, HAVING, IN, INCLUDES, LAST, LIKE, LIMIT, NOT, NULL, NULLS, OR, SELECT, USING, WHERE, WITH` # `allOrNone` Parameters in Composite and Collections Requests If a Composite request uses sObject Collections, there are two or more `allOrNone` parameters that can interact, one on the Composite request and one on each sObject Collections subrequest. - If the Composite request has `allOrNone` set to `true`, then the all-or-none behavior also applies to each of the sObject Collections subrequests, overriding the value of `allOrNone` in the subrequests. - If the Composite request has `allOrNone` set to `false`, then each sObject Collections subrequest behaves according to its value of `allOrNone`. Consider, for example, what happens with this job where a Composite request includes two items: an sObject Collections request and a request to create a Contact. The sObject Collections request tries to create two Accounts, one of which fails because there is already an existing Account with the same information. ```nolang POST https://MyDomainName.my.salesforce.com/services/data/v68.0/composite -H "Authorization: Bearer token" { "allOrNone" : outerFlag, "collateSubrequests" : false, "compositeRequest" : [ { "method" : "POST", "url" : "/services/data/v68.0/composite/sobjects", "body" : { "allOrNone" : innerFlag, "records" : [ { "attributes" : { "type" : "Account" }, "Name" : "Northern Trail Outfitters", "BillingCity" : "San Francisco" }, { "attributes" : { "type" : "Account" }, "Name" : "Easy Spaces", "BillingCity" : "Calgary" } ] }, "referenceId" : "newAccounts" }, { "method" : "POST", "url" : "/services/data/v68.0/sObject/Contact", "body" : { "FirstName" : "John", "LastName" : "Smith" }, "referenceId" : "newContact" } ] } ``` The `outerFlag` and `innerFlag` parameters are either `true` or `false`, which leads to four possible cases. **Case 1: `outerFlag` = `false`, `innerFlag` = `false`** In this case, neither request has `allOrNone` set to `true`, so neither request is rolled back. One account is created and one fails. ![diagram of results for this case](https://developer.salesforce.com/media/api-rest/all_or_none.composite.false_false.png) **Case 2: `outerFlag` = `false`, `innerFlag` = `true`** In this case, the inner sObject Collections request has `allOrNone` set to `true`, so it is rolled back. The outer Composite request is not rolled back. ![diagram of results for this case](https://developer.salesforce.com/media/api-rest/all_or_none.composite.false_true.png) **Case 3: `outerFlag` = `true`, `innerFlag` = `true`** In this case, both requests have `allOrNone` set to `true`, so they are both rolled back. ![diagram of results for this case](https://developer.salesforce.com/media/api-rest/all_or_none.composite.true_true.png) **Case 4: `outerFlag` = `true`, `innerFlag` = `false`** The response body for this case is: ```nolang { "compositeResponse" : [ { "body" : [ { "id" : "001R00000066cndIAA", "success" : true, "errors" : [ ] }, { "success" : false, "errors" : [ { "statusCode" : "DUPLICATES_DETECTED", "message" : "Use one of these records?", "fields" : [ ] } ] } ], "httpHeaders" : { }, "httpStatusCode" : 200, "referenceId" : "collection1" }, { "body" : [ { "errorCode" : "PROCESSING_HALTED", "message" : "The transaction was rolled back since another operation in the same transaction failed." } ], "httpHeaders" : { }, "httpStatusCode" : 400, "referenceId" : "newContact" } ] } ``` In this case, the inner sObject Collections request has `allOrNone` set to `false`, so it is not immediately rolled back. However, the outer Composite request has `allOrNone` set to `true` so it is rolled back, which also rolls back the inner sObject Collections request. ![diagram of results for this case](https://developer.salesforce.com/media/api-rest/all_or_none.composite.true_false.png) **note:** Even though the response body for sObject Collections request shows `"success" : true` for the creation of the first Account, the fact that the Composite request is rolled back means that the Account creation is rolled back. The final result is that the new Account is _not_ created. # AllOrNoneHeader Allows a call to roll back all changes unless all records are processed successfully. Without the AllOrNoneHeader header, records without errors are committed, while records with errors are marked as failed in the call results. This header is available in API version 20.0 and later. Even if the header is enabled, it's still necessary to inspect the `success` field in the call result for each record to identify records with errors. Each `success` field contains `true` or `false` indicating whether the call was processed successfully. If there is an error associated with at least one record, the `errors` field in the call result for the record gives more information on the error. If other records in the same call have no errors, their `errors` fields indicate that they were rolled back due to other errors. ## API Calls `create()`, `delete()`, `undelete()`, `update()`, `upsert()` ## Fields ### `allOrNone` **Type:** boolean **Description:** If `true`, any failed records in a call cause all changes for the call to be rolled back. Record changes aren't committed unless all records are processed successfully. The default is `false`. Some records can be processed successfully while others are marked as failed in the call results. ## Sample Code—Java This sample shows how to use the `AllOrNoneHeader`. It attempts to create two contacts. The second contact doesn’t have all required fields set and causes a failure on creation. Next, the sample sets the `allOrNone` field to `true`, and then attempts to create the contacts. Creating one of the contacts results in an error, so the entire transaction is rolled back and no contacts are created. ```codesegment public void allOrNoneHeaderSample() { try { // Create the first contact. SObject[] sObjects = new SObject[2]; Contact contact1 = new Contact(); contact1.setFirstName("Robin"); contact1.setLastName("Van Persie"); // Create the second contact. This contact doesn't // have a value for the required // LastName field so the create will fail. Contact contact2 = new Contact(); contact2.setFirstName("Ashley"); sObjects[0] = contact1; sObjects[1] = contact2; // Set the SOAP header to roll back the create unless // all contacts are successfully created. connection.setAllOrNoneHeader(true); // Attempt to create the two contacts. SaveResult[] sr = connection.create(sObjects); for (int i = 0; i < sr.length; i++) { if (sr[i].isSuccess()) { System.out.println("Successfully created contact with id: " + sr[i].getId() + "."); } else { // Note the error messages as the operation was rolled back // due to the all or none header. System.out.println("Error creating contact: " + sr[i].getErrors()[0].getMessage()); System.out.println("Error status code: " + sr[i].getErrors()[0].getStatusCode()); } } } catch (ConnectionException ce) { ce.printStackTrace(); } } } ``` # AllowFieldTruncationHeader Specifies that for some fields, when a string is too large, the operation fails. Without the header, strings for these fields are truncated. The `AllowFieldTruncationHeader` header affects the following datatypes: - anyType, if it represents one of the other datatypes in this list - email - encryptedstring - multipicklist - phone - picklist - string - textarea In API versions previous to 15.0, if a value for one of the listed fields is too large, the value is truncated. For API version 15.0 and later, if a value is too large, the operation fails and the fault code `STRING_TOO_LONG` is returned. `AllowFieldTruncationHeader` allows you to specify that the previous behavior, truncation, be used instead of the new behavior in API versions 15.0 and later. This header has no effect in versions 14.0 and earlier. ## API Calls [convertLead()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_convertlead.htm), [create()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_create.htm), [merge()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_merge.htm), [process()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_process.htm), [undelete()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_undelete.htm), [update()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_update.htm), and [upsert()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_upsert.htm) Apex: [`executeanonymous()`](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_executeanonymous.htm) ## Fields ### `allowFieldTruncation` **Type:** boolean **Description:** If `true`, truncate field values that are too long, which is the behavior in API versions 14.0 and earlier. Default is `false`: no change in behavior. If a `string` or `textarea` value is too large, the operation fails and the fault code `STRING_TOO_LONG` is returned. The following list shows the field types affected by truncation and this header: - anyType, if it represents one of the other datatypes in this list - email - encryptedstring - multipicklist - phone - picklist - string - textarea ## Sample Code—Java To create an account with a name that is too long for the `Name` field, use the AllowFieldTruncation header. This sample: 1. Creates an Account object with a name that exceeds the field limit of 255 characters. 2. Sends the create call, which fails because of the name field length. 3. Sets the `AllowFieldTruncationHeader` to `true` and retries the account creation, which succeeds. ```codesegment public void allowFieldTruncationSample() { try { Account account = new Account(); // Construct a string that is 256 characters long. // Account.Name's limit is 255 characters. String accName = ""; for (int i = 0; i < 256; i++) { accName += "a"; } account.setName(accName); // Construct an array of SObjects to hold the accounts. SObject[] sObjects = new SObject[1]; sObjects[0] = account; // Attempt to create the account. It will fail in API version 15.0 // and above because the account name is too long. SaveResult[] results = connection.create(sObjects); System.out.println("The call failed because: " + results[0].getErrors()[0].getMessage()); // Now set the SOAP header to allow field truncation. connection.setAllowFieldTruncationHeader(true); // Attempt to create the account now. results = connection.create(sObjects); System.out.println("The call: " + results[0].isSuccess()); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` # Alternatives to Cookies for User Tracking When creating websites and applications, the HTML ` ``` ## Attributes | Attribute Name | Attribute Type | Description | Required? | API Version | Access | | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | ----------- | ------ | | `frameborder` | Boolean | A Boolean value that specifies whether a border surrounds the inline frame. If not specified, this value defaults to false. |   | 10.0 | global | | `height` | String | The height of the inline frame expressed either as a percentage of the total available vertical space (for example, `height="50%"`) or as the number of pixels (for example, `height="300px"`). If not specified, this value defaults to 600 px. |   | 10.0 | global | | `id` | String | An identifier that allows other components in the page to reference the inline frame component. |   | 10.0 | global | | `rendered` | Boolean | A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. |   | 10.0 | global | | `scrolling` | Boolean | A Boolean value that specifies whether the inline frame can be scrolled. If not specified, this value defaults to true. |   | 10.0 | global | | `src` | String | The URL that specifies the initial contents of the inline frame. This URL can either be an external website or another page in the application. For example, to render the static resource `MyAsset` on a separate domain from Visualforce: |   | 10.0 | global | | `title` | String | The text to display as a tooltip when the user’s pointer hovers over this component. |   | 10.0 | global | | `width` | String | The width of the inline frame expressed either as a percentage of the total available horizontal space (for example, `width="80%"`) or as the number of pixels (for example, `width="600px"`). |   | 10.0 | global | Example `src`: ```apex ``` **See Also** - [Put Visualforce Pages on External Domains](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/quick-start/pages-quick-start-external-iframe.md) - [Referencing Untrusted Third-Party Content with iframes](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/resources/pages-resources-iframe.md) # apex:image A graphic image, rendered with the HTML `` tag. Use this component to get user input for a controller method that does not correspond to a field on an sObject. Only `` and `` can be used with sObject fields. This component supports [HTML pass-through attributes](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_html_features_pass_through_attributes.htm) using the "html-" prefix. Pass-through attributes are attached to the generated `` tag. ## Example ```apex ``` The example above renders the following HTML: ```html Description of image here ``` ## Resource Example ```apex ``` The example above renders the following HTML: ```html Description of image here ``` ## Zip Resource Example ```apex ``` The example above renders the following HTML: ```html ``` ## `IMAGEPROXYURL` Example ```apex ``` The example above renders the following HTML: ```html Description of image here ``` ## Attributes |Attribute Name|Attribute Type|Description|Required?|API Version|Access| |--------------|--------------|-----------|---------|-----------|------| |`alt`|String|An alternate text description of the image, used for Section 508 compliance.| |10.0|global| |`dir`|String|The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right).| |10.0|global| |`height`|String|The height at which this image should be displayed, expressed either as a relative percentage of the total available vertical space (for example, height="50%") or as a number of pixels (for example, height="100px"). If not specified, this value defaults to the dimension of the source image file.| |10.0|global| |`id`|String|An identifier that allows the image component to be referenced by other components in the page.| |10.0|global| |`ismap`|Boolean|A Boolean value that specifies whether this image should be used as an image map. If set to true, the image component must be a child of a commandLink component. If not specified, this value defaults to false.| |10.0|global| |`lang`|String|The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see [the W3C specifications](http://www.w3.org/TR/REC-html40/struct/dirlang.html).| |10.0|global| |`longdesc`|String|A URL that links to a longer description of the image.| |10.0|global| |`onclick`|String|The JavaScript invoked if the onclick event occurs--that is, if the user clicks the image.| |10.0|global| |`ondblclick`|String|The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the image twice.| |10.0|global| |`onkeydown`|String|The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key.| |10.0|global| |`onkeypress`|String|The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key.| |10.0|global| |`onkeyup`|String|The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key.| |10.0|global| |`onmousedown`|String|The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button.| |10.0|global| |`onmousemove`|String|The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer.| |10.0|global| |`onmouseout`|String|The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the image.| |10.0|global| |`onmouseover`|String|The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the image.| |10.0|global| |`onmouseup`|String|The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button.| |10.0|global| |`rendered`|Boolean|A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.| |10.0|global| |`style`|String|The style used to display the image component, used primarily for adding inline CSS styles.| |10.0|global| |`styleClass`|String|The style class used to display the image component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.| |10.0|global| |`title`|String|The text to display as a tooltip when the user's mouse pointer hovers over this component.| |10.0|global| |`url`|String|The path to the image displayed, expressed either as a URL or as a static resource or document merge field.| |10.0|global| |`usemap`|String|The name of a client-side image map (an HTML map element) for which this element provides the image.| |10.0|global| |`value`|Object|The path to the image displayed, expressed either as a URL or as a static resource or document merge field.| |10.0|global| |`width`|String|The width at which this image is displayed, expressed either as a relative percentage of the total available horizontal space (for example, width="50%") or as a number of pixels (for example, width="100px"). If not specified, this value defaults to the dimension of the source image file.| |10.0|global| # apex\:include A component that inserts a second Visualforce page into the current page. The entire page subtree is injected into the Visualforce DOM at the point of reference and the scope of the included page is maintained. If content should be stripped from the included page, use the `` component instead. ## Example ```apex
``` The example above renders the following HTML: ```html (page) This is the page.
(include) This is text from another page. ``` ## Attributes | Attribute Name | Attribute Type | Description | Required? | API Version | Access | | -------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------- | ------ | | `id` | String | An identifier that allows the inserted page to be referenced by other components in the page. |   | 10.0 | global | | `pageName` | ApexPages.PageReference | The Visualforce page whose content should be inserted into the current page. For this value, specify the name of the Visualforce page or use merge-field syntax to reference a page or PageReference. | Yes | 10.0 | global | | `rendered` | Boolean | A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. |   | 10.0 | global | **See Also** - [Referencing an Existing Page with \](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/templates/pages-templates-include.md) # apex:includeLightning Includes the Lightning Components for Visualforce JavaScript library, lightning.out.js, from the correct Salesforce domain. **note:** The Lightning Components for Visualforce JavaScript library loads from the org that the Visualforce page is in, so your Lightning Out app must exist in the same org as the Visualforce page. ## Attributes |Attribute Name|Attribute Type|Description|Required?|API Version|Access| |--------------|--------------|-----------|---------|-----------|------| |`id`|String|An identifier that allows the component to be referenced by other components in the page.| |14.0|global| |`rendered`|Boolean|A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.| |14.0|global| **See Also** - [Render Lightning Runtime for Flows in a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/flows/pages-flows-lightningruntime.md) # apex:includeScript A link to a JavaScript library that can be used in the Visualforce page. When specified, this component injects a script reference into the `` element of the generated HTML page. Multiple references to the same script are de-duplicated, making this component safe to use inside an iteration component. This might occur if, for example, you use an `` inside a custom component, and then use that component inside an `` iteration. For performance reasons, you might choose to use a static JavaScript tag before your closing `` tag, rather than this component. If you do, you'll need to manage de-duplication yourself. This component supports [HTML pass-through attributes](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_html_features_pass_through_attributes.htm) using the "html-" prefix. Pass-through attributes are attached to the generated ` ``` Here, we reference a custom message channel with a formula expression `{!$MessageChannel.SampleMessageChannel__c}`. This expression creates a token that we assign to the variable `SAMPLEMC`. This token is unique to your custom message channel and can be used within the Lightning message service API methods. The syntax `SampleMessageChannel__c` refers to a custom instance of the `LightningMessageChannel` metadata type. The `__c` suffix indicates that it’s custom, but note that it isn’t a custom object. See [Create a Message Channel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-publish.md) to learn more. If your org has a namespace, don’t include it in your message channel expression. For example, if your org’s namespace is MyNamespace, the message channel expression remains `"{!$MessageChannel.SampleMessageChannel__c}"`. ## Use Message Channels Created Outside Your Org To use message channels from packages created by developers outside of your org, reference them with the syntax `{!$MessageChannel.Namespace_name__c}`. For example, if `SampleMessageChannel` wasn’t local to your org and came from a package with the namespace SamplePackageNamespace, the syntax would be `{$MessageChannel.SamplePackageNamespace__SampleMessageChannel__c}`. - **[Create a Message Channel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-create.md)** To create a Lightning Message Channel in your org, use the LightningMessageChannel metadata type. - **[Publish on a Message Channel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-publish.md)** To publish on a Message Channel from a Visualforce page, include the `$MessageChannel` global variable in your page's JavaScript code and write a method that calls `sforce.one.publish()`. - **[Subscribe and Unsubscribe from a Message Channel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-subscribe.md)** To subscribe and unsubscribe from a message channel, use the `sforce.one.subscribe()` and `sforce.one.unsubscribe()` methods. - **[Considerations and Limitations](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-considerations.md)** Keep these considerations and limitations in mind when working with Lightning message service in Visualforce. **See Also** - [Blog: Lightning Message Service](https://developer.salesforce.com/blogs/2019/10/lightning-message-service-developer-preview.html) - [Lightning Web Components Developer Guide: Communicating Across the DOM with Lightning Message Service](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/message_channel_intro.htm) - [Lightning Aura Components Developer Guide: Communicating Across the DOM with Lightning Message Service](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/message_channel_intro.htm) - [Open CTI Developer Guide: Lightning Message Service Methods for Lightning Experience](https://developer.salesforce.com/docs/atlas.en-us.api_cti.meta/api_cti/sforce_api_cti_methods_lms.htm) # Communicating with Events The framework uses event-driven programming. You write handlers that respond to interface events as they occur. The events may or may not have been triggered by user interaction. In the Aura Components programming model, events are fired from JavaScript controller actions. Events can contain attributes that can be set before the event is fired and read when the event is handled. Events are declared by the `aura:event` tag in a .evt resource, and they can have one of two types: component or application. ## Component Events A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event. ## Application Events Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified. **note:** Always try to use a component event instead of an application event, if possible. Component events can only be handled by components above them in the containment hierarchy so their usage is more localized to the components that need to know about them. Application events are best used for something that should be handled at the application level, such as navigating to a specific record. Application events allow communication between components that are in separate parts of the application and have no direct containment relationship. - **[Actions and Events](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-and-actions.md)** The framework uses events to communicate data between components. Events are usually triggered by a user action. - **[Handling Events with Client-Side Controllers](https://developer.salesforce.com/docs/platform/aura-platform/js/js-client-side-controller.md)** A client-side controller handles events within a component. It’s a JavaScript resource that defines the functions for all of the component’s actions. - **[Component Events](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-component.md)** A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event. - **[Application Events](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-application.md)** Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified. - **[Event Handler Behavior for Active Components](https://developer.salesforce.com/docs/platform/aura-platform/guide/event-handler-active-components.md)** To prevent active event handlers on cached pages from causing problems, add a workaround to your code to check if the component is still visible. To avoid this scenario and the workaround, use Lightning message service instead to communicate across the DOM within a Lightning page. The default scope used by Lightning message service channels publishes only to active components. - **[Event Handling Lifecycle](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-overview.md)** - **[Advanced Events Example](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-demo.md)** - **[Firing Events from Non-Aura Code](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-external.md)** You can fire Aura events from JavaScript code outside an Aura app. For example, your Aura app might need to call out to some non-Aura code, and then have that code communicate back to your Aura app once it's done. - **[Events Best Practices](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-best-practices.md)** Here are some best practices for working with events. - **[Events Fired During the Rendering Lifecycle](https://developer.salesforce.com/docs/platform/aura-platform/components/components-lifecycle.md)** A component is instantiated, rendered, and rerendered during its lifecycle. A component rerenders only when there’s a programmatic or value change that requires a rerender. For example, if a browser event triggers an action that updates the component’s data, the component rerenders. - **[Events Handled in the Salesforce Mobile App and Lightning Experience](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-one.md)** The Salesforce mobile app and Lightning Experience handle some events, which you can fire in your Aura component. - **[System Events](https://developer.salesforce.com/docs/platform/aura-platform/guide/events-system.md)** The framework fires several system events during its lifecycle. # Compact Layouts Returns a list of compact layouts for multiple objects. This resource is available in REST API version 31.0 and later. This resource returns the primary compact layout for a set of objects. The set of objects is specified using a query parameter. Up to 100 objects can be queried at once. **note:** PersonAccount isn’t supported for bulk queries. If you want to get the primary compact layout for PersonAccount, get it directly from `/services/data/v68.0/sobjects/Account/describe/compactLayouts/primaryPersonAccount`. ## Syntax **URI:** `/services/data/vXX.X/compactLayouts?q=objectList` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request parameters** |Parameter|Description| |---------|-----------| |`q`|A comma-delimited list of objects. The primary compact layout for each object in this list will be returned in the response of this resource.| ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/compactLayouts?q=Account,Contact,CustomObj__c -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang { "Account" : { "actions" : [ { "behavior" : null, "content" : null, "contentSource" : null, "custom" : false, "encoding" : null, "height" : null, "icons" : null, "label" : "Call", "menubar" : false, "name" : "CallHighlightAction", "overridden" : false, "resizeable" : false, "scrollbars" : false, "showsLocation" : false, "showsStatus" : false, "toolbar" : false, "url" : null, "width" : null, "windowPosition" : null }, ... "id" : "0AHD000000000AbOAI", "label" : "Custom Account Compact Layout", "name" : "Custom_Account_Compact_Layout" }, "Contact" : { "actions" : [ { "behavior" : null, "content" : null, "contentSource" : null, "custom" : false, "encoding" : null, "height" : null, "icons" : null, "label" : "Call", "menubar" : false, "name" : "CallHighlightAction", "overridden" : false, "resizeable" : false, "scrollbars" : false, "showsLocation" : false, "showsStatus" : false, "toolbar" : false, "url" : null, "width" : null, "windowPosition" : null }, ... "id" : null, "label" : "System Default", "name" : "SYSTEM" } "CustomObj__c" : { "actions" : [ { "behavior" : null, "content" : null, "contentSource" : null, "custom" : false, "encoding" : null, "height" : null, "icons" : null, "label" : "Call", "menubar" : false, "name" : "CallHighlightAction", "overridden" : false, "resizeable" : false, "scrollbars" : false, "showsLocation" : false, "showsStatus" : false, "toolbar" : false, "url" : null, "width" : null, "windowPosition" : null }, ... "id" : null, "imageItems" : null, "label" : "System Default", "name" : "SYSTEM" } } ``` # Comparing JavaScript Remoting and \ The `` component also lets you call controller action methods through JavaScript. In general, `` is easier to use and requires less code, while JavaScript remoting offers more flexibility. Here are some specific differences between the two. - The `` tag: - lets you specify rerender targets - submits the form - doesn’t require you to write any JavaScript - JavaScript remoting: - lets you pass parameters - provides a callback - requires you to write some JavaScript # Comparing JavaScript Remoting and Remote Objects JavaScript Remoting and Remote Objects offer similar features, and both are useful tools for creating dynamic, responsive pages. They have some important differences that you should consider before choosing which to use. In general, Remote Objects is well-suited to pages that need to perform only simple Create-Read-Update-Delete, or “CRUD”, object access. JavaScript Remoting is better suited to pages that access higher-level server actions. Remote Objects lets you get up and running quickly without a lot of ceremony, while JavaScript Remoting is suited for more complex applications that require some up front API-style design work. Visualforce Remote Objects: - Makes basic “CRUD” object access easy - Doesn’t require any Apex code - Supports minimal server-side application logic - Doesn’t provide automatic relationship traversals; you must look up related objects yourself JavaScript Remoting: - Requires both JavaScript and Apex code - Supports complex server-side application logic - Handles complex object relationships better - Uses network connections (even) more efficiently # Comparing setResumeCheckpoint() and EventBus.RetryableException Determine which method is most suitable for resuming a platform event trigger. |`setResumeCheckpoint()` Method|`EventBus.RetryableException`| |------------------------------|-----------------------------| |Use `setResumeCheckpoint()` when the trigger has processed event messages successfully before an unhandled exception occurs, such as a limit exception. After the exception, the trigger resumes after the last checkpointed event message.|Throw the `EventBus.RetryableException` to reprocess events when you expect an external condition to change or a transient error to go away.| |Trigger execution continues after `setResumeCheckpoint()`.|Trigger execution halts after the `EventBus.RetryableException` is thrown.| |DML operations performed are committed.|DML operations performed before the exception is thrown are rolled back and not committed.| |When the trigger fires again, only the event messages after the one with the specified replay ID are resent, in addition to any new event messages.|When the trigger fires again, all event messages from the previous batch are resent in the new batch, in addition to any new event messages.| |These `TriggerContext` properties don’t apply and aren’t populated: `retries` and `lastError`.|These `TriggerContext` properties are populated: `retries` and `lastError`.| |No limit on how many times you can set a checkpoint with `setResumeCheckpoint()` and how many times the trigger can resume from the checkpoint after an unhandled exception occurs.|You can retry the trigger nine times after its initial run by throwing `EventBus.RetryableException`.| To use both `setResumeCheckpoint()` and `EventBus.RetryableException`, follow the platform event trigger template shown in the Use a Platform Event Trigger Template section of the [Apply Best Practices for Writing Platform Event Triggers](https://trailhead.salesforce.com/content/learn/modules/platform-events-debugging/apply-best-practices-writing-platform-triggers) Trailhead. Other use cases that use both together are not supported. # Comparison Operators SOQL queries can include comparison operators, such as =, \<, >, IN, and LIKE in the field expression of a `WHERE` clause, which you use in a `SELECT` statement. You can also use comparison operators to create complex queries with semi-joins and anti-joins. The following table lists the `comparisonOperator` values that are used in `fieldExpression` syntax. **note:** Comparisons on strings are case-sensitive for unique case-sensitive fields. For all other fields, comparisons are case-insensitive and use the locale of the user who executes the query. Text stored in Salesforce doesn’t have an associated language or locale, so locale-specific casing rules can affect which records a query returns. For example, Turkish has separate dotted and dotless character pairs: `i`/`İ` and `ı`/`I`. For a user with the Turkish locale, a filter that contains `Service` can match `Service` and `SERVİCE`, but not `SERVICE`. You can’t specify a different locale for the comparison in SOQL. | Operator | Name | Description | | ------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `=` | `Equals` | Expression is true if the value in the fieldName equals the value in the expression. | | `!=` | `Not equals` | Expression is true if the value in the fieldName doesn’t equal the specified value. | | `<` | `Less than` | Expression is true if the value in the fieldName is less than the specified value. | | `<=` | `Less or equal` | Expression is true if the value in the fieldName is less than or equal to the specified value. | | `>` | `Greater than` | Expression is true if the value in the fieldName is greater than the specified value. | | `>=` | `Greater or equal` | Expression is true if the value in the fieldName is greater than or equal to the specified value. | | `LIKE` | `Like` | Expression is true if the value in the fieldName matches the characters of the text string in the specified value. The text string in the specified value must be enclosed in single quotes. The `LIKE` operator is supported for string fields only. The operator provides a mechanism for matching partial text strings and includes support for the `%` wildcard (matches zero or more characters), the `_` wildcard (matches exactly one character), and the escaping of special characters `%` or `_`. | | `IN` | `IN` | If the value equals any one of the values in a `WHERE` clause. The string values for `IN` must be in parentheses and surrounded by single quotes. You can query values in a field where another field on the same object has a specified set of values, using `IN`. You can also use `IN` and `NOT IN` for semi-joins and anti-joins when querying on ID (primary key) or reference (foreign key) fields. | | `NOT IN` | `NOT IN` | If the value doesn’t equal any of the values in a `WHERE` clause. The string values for `NOT IN` must be in parentheses and surrounded by single quotes. | | `INCLUDES EXCLUDES` |   | Applies only to multi-select picklists. See [Query Multi-Select Picklists](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-querying-multiselect-picklists.md). | **Note:** Don’t use the backslash (\\) character in a search except to escape a special character. See [Quoted String Escape Sequences](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-quotedstringescapes.md). This example `LIKE` query matches Appleton, Apple, and Appl, but not Bappl. ```codesegment SELECT AccountId, FirstName, lastname FROM Contact WHERE lastname LIKE 'appl%' ``` Example `IN`: ```codesegment SELECT Name FROM Account WHERE BillingState IN ('California', 'New York') ``` Example `NOT IN`: ```codesegment SELECT Name FROM Account WHERE BillingState NOT IN ('California', 'New York') ``` **Note:** The logical operator `NOT` is unrelated to this comparison operator. ## Semi-Joins with `IN` and Anti-Joins with `NOT IN` A semi-join is a subquery on another object in an `IN` clause to restrict the records returned. An anti-join is a subquery on another object in a `NOT IN` clause to restrict the records returned. You can create more complex queries by replacing the list of values in the `IN` or `NOT IN` clause with a subquery. The subquery can filter by ID (primary key) or reference (foreign key) fields. Sample uses of semi-joins and anti-joins include: - Get all contacts for accounts that have an opportunity with a particular record type. - Get all open opportunities for accounts that have active contracts. - Get all open cases for contacts that are the decision maker on an opportunity. - Get all accounts that don’t have any open opportunities. If you filter by an ID field, you can create parent-to-child semi- or anti-joins, such as `Account` to `Contact`. If you filter by a reference field, you can create child-to-child semi- or anti-joins, such as `Contact` to `Opportunity`, or child-to-parent semi- or anti-joins, such as `Opportunity` to `Account`. **ID Field Semi-Join** You can include a semi-join in a `WHERE` clause. For example, this query returns account IDs if an associated opportunity is lost: ```codesegment SELECT Id, Name FROM Account WHERE Id IN ( SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Lost' ) ``` This example is a parent-to-child semi-join from `Account` to `Opportunity`. Notice that the left operand, `Id`, of the `IN` clause is an ID field. The subquery returns a single field of the same type as the field to which it’s compared. For restrictions that prevent unnecessary processing of semi-join queries, see [Considerations](#considerations-for-semi-join-and-anti-join-queries). **Reference Field Semi-Join** The following query returns task IDs for all contacts in `Twin Falls`: ```codesegment SELECT Id FROM Task WHERE WhoId IN ( SELECT Id FROM Contact WHERE MailingCity = 'Twin Falls' ) ``` Notice that the left operand, `WhoId`, of the `IN` clause is a reference field. An interesting aspect of this query is that `WhoId` is a polymorphic reference field as it can point to a contact or a lead. The subquery restricts the results to contacts. **ID Field Anti-Join** This query returns account IDs for all accounts that don’t have any open opportunities: ```codesegment SELECT Id FROM Account WHERE Id NOT IN ( SELECT AccountId FROM Opportunity WHERE IsClosed = false ) ``` **Reference Field Anti-Join** This query returns opportunity IDs for all contacts whose source isn’t `Web`: ```codesegment SELECT Id FROM Opportunity WHERE AccountId NOT IN ( SELECT AccountId FROM Contact WHERE LeadSource = 'Web' ) ``` This example is a child-to-child anti-join from `Opportunity` to `Contact`. **Multiple Semi-Joins or Anti-Joins** You can combine semi-join or anti-join clauses in a query. For example, the following query returns account IDs that have open opportunities if the last name of the contact associated with the account is like the last name “Apple”: ```codesegment SELECT Id, Name FROM Account WHERE Id IN ( SELECT AccountId FROM Contact WHERE LastName LIKE 'apple%' ) AND Id IN ( SELECT AccountId FROM Opportunity WHERE isClosed = false ) ``` **note:** You can use at most two subqueries in a single semi-join or anti-join query. Multiple semi-joins and anti-join queries are also subject to existing limits on subqueries per query. **Semi-Joins or Anti-Joins Evaluating Relationship Queries** You can create a semi-join or anti-join that evaluates a [relationship query](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships.md) in a `SELECT` clause. For example, the following query returns opportunity IDs and their related line items if the opportunity's line item total value is more than \$10,000: ```codesegment SELECT Id, (SELECT Id from OpportunityLineItems) FROM Opportunity WHERE Id IN ( SELECT OpportunityId FROM OpportunityLineItem WHERE totalPrice > 10000 ) ``` ## Considerations for Semi-Join and Anti-Join Queries Because a great deal of processing work is required for semi-join and anti-join queries, Salesforce imposes the following restrictions to maintain the best possible performance: - **Basic limits:** - You can’t use more than two `IN` or `NOT IN` statements per `WHERE` clause. - You can’t use the `NOT` operator as a conjunction with semi-joins and anti-joins. Using it converts a semi-join to an anti-join, and the reverse. Instead of using the `NOT` operator, write the query in the appropriate semi-join or anti-join form. - **Main query limits:** The following restrictions apply to the main `WHERE` clause of a semi-join or anti-join query: - The left operand must query a single ID (primary key) or reference (foreign key) field. The selected field in a subquery can be a reference field. For example: ```codesegment SELECT Id FROM Idea WHERE (Id IN (SELECT ParentId FROM Vote WHERE CreatedDate > LAST_WEEK AND Parent.Type='Idea')) ``` - The left operand can't use relationships. For example, the following semi-join query is invalid due to the `Account.Id` relationship field: ```soql SELECT Id FROM Contact WHERE Account.Id IN ( SELECT ... ) ``` - **Subquery limits:** - A subquery must query a field referencing the same object type as the main query. - There’s no limit on the number of records matched in a subquery. Standard SOQL query limits apply to the main query. - The selected column in a subquery must be a foreign key field, and can’t traverse relationships. This limit means that you can’t use dot notation in a selected field of a subquery. For example, the following query is valid: ```codesegment SELECT Id, Name FROM Account WHERE Id IN ( SELECT AccountId FROM Contact WHERE LastName LIKE 'Brown_%' ) ``` Using `Account.Id` (dot notation) instead of AccountId isn’t supported. Similarly, subqueries like `Contact.AccountId FROM Case` are invalid. - You can’t query on the same object in a subquery as in the main query. You can write such self semi-join queries without using semi-joins or anti-joins. For example, the following self semi-join query is invalid: ```soql SELECT Id, Name FROM Account WHERE Id IN ( SELECT ParentId FROM Account WHERE Name = 'myaccount' ) ``` Rewrite the query in a valid form, for example: ```codesegment SELECT Id, Name FROM Account WHERE Parent.Name = 'myaccount' ``` - You can’t nest a semi-join or anti-join statement in another semi-join or anti-join statement. - You can’t use semi-joins and anti-joins in a `HAVING` clause. - You can use semi-joins and anti-joins in the main `WHERE` statement, but not in a subquery `WHERE` statement. For example, the following query is valid: ```codesegment SELECT Id FROM Idea WHERE (Idea.Title LIKE 'Vacation%') AND (Idea.LastCommentDate > YESTERDAY) AND (Id IN (SELECT ParentId FROM Vote WHERE CreatedById = '005x0000000sMgYAAU' AND Parent.Type='Idea')) ``` The following query is invalid since the nested query is an extra level deep: ```soql SELECT Id FROM Idea WHERE ((Idea.Title LIKE 'Vacation%') AND (CreatedDate > YESTERDAY) AND (Id IN (SELECT ParentId FROM Vote WHERE CreatedById = '005x0000000sMgYAAU' AND Parent.Type='Idea') ) OR (Idea.Title like 'ExcellentIdea%')) ``` - You can’t use subqueries with `OR`. - `COUNT`, `FOR UPDATE`, `ORDER BY`, and `LIMIT` aren’t supported in subqueries. - The following objects aren’t currently supported in subqueries: - ActivityHistory - Attachments - Event - Note - OpenActivity - Tags (AccountTag, ContactTag, and all other tag objects) - Task # Compatibility and Requirements AppReviewService 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 AppReviewService 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.** AppReviewService is available in Lightning apps that are distributed using Mobile Publisher for Experience Cloud. AppReviewService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Mobile Publisher for Experience Cloud mobile app on a compatible iOS or Android mobile device. See [Requirements for Mobile Publisher for Experience Cloud](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements_commun.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. AppReviewService is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** the Mobile Publisher for Experience Cloud app. The AppReviewService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only AppReviewService constants and utility functions. Attempting any app review-related operation will fail. # Compatibility and Requirements BarcodeScanner 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 BarcodeScanner runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a web browser, whether the browser runs on a desktop or mobile device.** BarcodeScanner is available in Lightning apps distributed using: - Salesforce Mobile app - Mobile Publisher for Salesforce App - Mobile Publisher for Experience Cloud **note:** The Field Service Mobile app provides an alternative implementation of BarcodeScanner. See [Scan Barcodes on a Mobile Device](https://developer.salesforce.com/docs/atlas.en-us.field_service_dev.meta/field_service_dev/fsl_dev_mobile_lwc_barcode_scanner.htm) in the _Field Service Developer Guide_ for details. BarcodeScanner is fully functional when used in a Lightning app or Lightning site run from one of these Salesforce apps on a compatible iOS or Android mobile device. See [Requirements for the Salesforce Mobile App](https://help.salesforce.com/articleView?id=salesforce_app_requirements.htm&type=5), or the requirements page for your target mobile app, for specific device and operating system requirements. BarcodeScanner is **not** fully functional when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the mobile apps listed above. The BarcodeScanner API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only BarcodeScanner constants and utility functions. Attempting any scanning operation will fail. ## Supported Barcode Types BarcodeScanner can recognize the following [standard barcode symbologies](https://www.barcodefaq.com/barcode-match/). (References not affiliated with Salesforce.) | Barcode Symbology Standard | BarcodeScanner Type (`barcodeTypes`) | | --------------------------------------------------------------- | ------------------------------------ | | [Code 128](https://www.barcodefaq.com/1d/code-128/) | `CODE_128` | | [Code 39](https://www.barcodefaq.com/1d/code-39/) | `CODE_39` | | [Code 93](https://www.barcodefaq.com/barcode-match/) | `CODE_93` | | [Data Matrix](https://www.barcodefaq.com/2d/data-matrix/) | `DATA_MATRIX` | | [EAN-13 / GTIN-13](https://www.barcodefaq.com/1d/upc-ean/) | `EAN_13` | | [EAN-8 / GTIN-8](https://www.barcodefaq.com/1d/upc-ean/) | `EAN_8` | | [Interleaved 2 of 5](https://www.barcodefaq.com/barcode-match/) | `ITF` | | [PDF417](https://www.barcodefaq.com/2d/pdf417/) | `PDF_417` | | [QR-Code](https://www.barcodefaq.com/2d/qr-code/) | `QR` | | [UPC-A / GTIN-12](https://www.barcodefaq.com/1d/upc-ean/) | `UPC_A` | | [UPC-E / GTIN-12](https://www.barcodefaq.com/1d/upc-ean/) | `UPC_E` | To access or compare barcode types in code, use the [`barcodeTypes`](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-barcodescanner-constants.html) constant. BarcodeScanner doesn’t attempt to interpret the value found in a barcode. The contents of the barcode are decoded into a string value. It’s up to the controlling component or application to further parse and interpret the result and decide what to do with it. For more information about barcode standards and symbologies, see [Barcoding for Beginners](https://www.barcodefaq.com/barcoding-for-beginners/) (not affiliated with Salesforce). # Compatibility and Requirements 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.** BiometricsService is available in Lightning apps distributed using: - Salesforce Mobile app - Mobile Publisher for Experience Cloud BiometricsService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Requirements for Mobile Publisher for Experience Cloud](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements_commun.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. BiometricsServiceis **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the apps listed above. The BiometricsService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only BiometricsService constants and utility functions. Attempting any biometrics related operation will fail. # Compatibility and Requirements CalendarService 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 CalendarService 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. ** CalendarService is available in Lightning apps distributed using: - Mobile Publisher for Experience Cloud CalendarService is fully functional when used in a Lightning app run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Requirements for Mobile Publisher for Experience Cloud ](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements_commun.htm&type=5) or the requirements page for your target mobile app for specific device and operating system requirements. CalendarService is **not** fully functional when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the mobile apps listed above. The CalendarService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser–desktop or mobile–it can use only CalendarService constants and utility functions. Attempting any calendar-related operation will fail. # Compatibility and Requirements 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.** ContactsService is available in Lightning apps distributed using: - Mobile Publisher for Salesforce App - Mobile Publisher for Experience Cloud ContactsService is fully functional when used in a Lightning app or Lightning site run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Requirements for the Salesforce Mobile App](https://help.salesforce.com/articleView?id=salesforce_app_requirements.htm&type=5), [Requirements for Mobile Publisher for Salesforce App](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. ContactsService is **not** fully functional when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the mobile apps listed above. The ContactsService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only ContactsService constants and utility functions. Attempting any contacts-related operation will fail. # Compatibility and Requirements DocumentScanner 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 DocumentScanner 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.** DocumentScanner is available in Lightning apps distributed using: - Salesforce Mobile app - Salesforce Field Service app DocumentScanner is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Requirements for the Salesforce Mobile App](https://help.salesforce.com/articleView?id=salesforce_app_requirements.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. DocumentScanner is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the apps listed above. The DocumentScanner API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only DocumentScanner constants and utility functions. Attempting any document scanning operation will fail. # Compatibility and Requirements GeofencingService 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 GeofencingService 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.** GeofencingService is available in Lightning apps distributed using: - Salesforce Field Service app GeofencingService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Field Service Mobile App Requirements](https://help.salesforce.com/s/articleView?id=service.mfs_requirements.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. GeofencingService is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the listed apps. The GeofencingService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only GeofencingService constants and utility functions. Attempting any geofencing-related operation results in failure. # Compatibility and Requirements 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.** HealthService is available in Lightning apps that are distributed using Mobile Publisher for Experience Cloud. HealthService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Mobile Publisher for Experience Cloud mobile app on a compatible iOS or Android mobile device. On iOS, HealthService requires iOS 17 or later and reads and writes data through Apple HealthKit. On Android, HealthService reads and writes data through Android Health Connect, which the user must have installed. See [Requirements for Mobile Publisher for Experience Cloud](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements_commun.htm&type=5), or the requirements page for your target mobile app, for specific device and operating system requirements. HealthService is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** the Mobile Publisher for Experience Cloud app. The HealthService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only HealthService constants and utility functions. Any health data operation fails. ## Grant the Host App Access to the Health Store The device’s health platform requires the host app to declare its intent to read and write health data before HealthService can access it. - **iOS**: The host app must declare the HealthKit entitlement and provide the `NSHealthShareUsageDescription` and `NSHealthUpdateUsageDescription` strings in its `Info.plist` file. - **Android**: The host app must declare the `android.permission.health.READ_WEIGHT` and `android.permission.health.WRITE_WEIGHT` permissions, and disclose its use of health data in its Google Play Console Health Data Safety form. # Compatibility and Requirements LocationService is a JavaScript module that provides an API to Lightning web components to make mobile hardware and platform (operating system) features available in JavaScript. LocationService **requires** access to device hardware and device platform APIs. This access is only available when LocationService 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.** LocationService is available in Lightning apps distributed using: - Salesforce Mobile app - Mobile Publisher for Salesforce App - Mobile Publisher for Experience Cloud - Field Service Mobile app LocationService is fully functional when used in a Lightning app or Lightning site run from one of these Salesforce apps on a compatible iOS or Android mobile device. See [Requirements for the Salesforce Mobile App](https://help.salesforce.com/articleView?id=salesforce_app_requirements.htm&type=5), [Requirements for Mobile Publisher for Salesforce App](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_requirements.htm&type=5), [Field Service Mobile App Requirements](https://help.salesforce.com/s/articleView?id=service.mfs_requirements.htm&type=5), or the requirements page for your target mobile app, for specific device and operating system requirements. LocationService is **not** fully functional when running on other devices, such as a desktop, or when running in a standard web browser, even on a mobile device. It **requires** one of the mobile apps listed above. The LocationService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only LocationService constants and utility functions. Attempting to use location-specific features will fail. LocationService only provides location data, in the form of geo-coordinates and some metadata. What you do with the location data is up to your component to parse, compare, and place in context—for example, to calculate distance, display on a map, and so on. # Compatibility and Requirements NFCService 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 NFCService 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.** NFCService is available in Lightning apps distributed using: - Salesforce Mobile app - Salesforce Field Service app NFCService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Requirements for the Salesforce Mobile App](https://help.salesforce.com/articleView?id=salesforce_app_requirements.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. NFCService is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the apps listed above. The NFCService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only NFCService constants and utility functions. Attempting any NFC-related operation will fail. # Compatibility and Requirements 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.** PaymentsService is available in Lightning apps distributed using: - Salesforce Field Service app PaymentsService is fully functional when used in a Lightning app or Lightning site that’s run from a compatible Salesforce mobile app on a compatible iOS or Android mobile device. See [Field Service Mobile App Requirements](https://help.salesforce.com/s/articleView?id=service.mfs_requirements.htm&type=5), or the requirements page for your target mobile app for specific device and operating system requirements. PaymentsService is **not** fully available when running on other devices, such as a desktop, or when running in a web browser, even on a mobile device. It **requires** one of the listed apps. The PaymentsService API is accessible in Lightning Experience on all devices, so your code won’t fail due to missing functions. However, when your app runs in a browser—desktop or mobile—it can use only PaymentsService constants and utility functions. Attempting any payment-related operation results in failure. # Compile Consent Settings Gets consent details based on a single action, like email or track, across specific consent management objects when the records have a lookup relationship. This resource is available in REST API version 45.0 and later. To call Consent API, you must have either the View All Data or the Allow User Access to Privacy Data user permission. Requiring a perm ensures that the System Administrator gives explicit permission. This API accesses org-wide consent data, such as links between records and the value of consent flags, not just records to which the user ordinarily has access. Consent API gets consent details based on a single action, like email or track, across the Contact, Contact Point Type Consent, Data Use Purpose, Individual, Lead, Person Account, and User objects when the records have a lookup relationship. When you select *email* as the action, the API only aggregates consent for records that contain the same email address. If the record ID specified in the URI is associated with a record that contains a different email address, the consent settings of the associated record aren’t included in the API response. The Consent API can't locate records in which the email address field is protected by Platform Encryption. **note:** When the API compares consent settings across records, it doesn’t incorporate settings from converted leads. ||||| |-|-|-|-| |**Action**|**Fields Consulted**|**API Response**|**Response Schema**| |email|
  • Contact.HasOptedOutOfEmail
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
  • Lead.HasOptedOutOfEmail
  • PersonAccount.HasOptedOutOfEmail
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `email` after this table.| |fax|
  • Contact.HasOptedOutOfFax
  • DataUsePurpose.Name
  • Lead.HasOptedOutOfFax
  • PersonAccount.HasOptedOutOfFax
|Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Lead, or Person Account object exists.|See example response schema for `fax` after this table.| |geotrack|
  • DataUsePurpose.Name
  • Individual.HasOptedOutGeoTracking
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `geotrack` after this table.| |mail|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `mail` after this table.| |phone|
  • Contact.DoNotCall
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
  • Lead.DoNotCall
  • PersonAccount.DoNotCall
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `phone` after this table.| |portability|
  • DataUsePurpose.Name
  • Individual.SendIndividualData
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `portability` after this table.| |process|
  • DataUsePurpose.Name
  • Individual.HasOptedOutProcessing
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `process` after this table.| |profile|
  • DataUsePurpose.Name
  • Individual.HasOptedOutProfiling
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `profile` after this table.| |shouldforget|
  • DataUsePurpose.Name
  • Individual.ShouldForget
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `shouldforget` after this table.| |social|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `social` after this table.| |solicit|
  • DataUsePurpose.Name
  • Individual.HasOptedOutSolicit
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `solicit` after this table.| |storepiielsewhere|
  • DataUsePurpose.Name
  • Individual.CanStorePiiElsewhere
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `storepiielsewhere` after this table.| |track|
  • DataUsePurpose.Name
  • Individual.HasOptedOutTracking
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `track` after this table.| |web|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `web` after this table.| Example response schema for `email`: ```nolang { "" : { "result" : "", "proceed" : { "emailResult" : "", email : “” } } } ``` Example response schema for `fax`: ```nolang { "" : { "result" : "", "proceed" : { "faxResult" : "", fax : "" } } } ``` Example response schema for `geotrack`: ```nolang { "" : { "result" : "", "proceed" : { "geotrackResult" : "", "geotrack" : "" } } } ``` Example response schema for `mail`: ```nolang { "" : { "result" : "", "proceed" : { "mailingResult" : "", "mail" : "" } } } ``` Example response schema for `phone`: ```nolang { "" : { "result" : "", "proceed" : { "phoneResult" : "", "phone" : "" } } } ``` Example response schema for `portability`: ```nolang { "" : { "result" : "", "proceed" : { "portabilityResult" : "", "portability" : "" } } } ``` Example response schema for `process`: ```nolang { "" : { "result" : "", "proceed" : { "processResult" : "", "process" : "" } } } ``` Example response schema for `profile`: ```nolang { "" : { "result" : "", "proceed" : { "profileResult" : "", "profile" : "" } } } ``` Example response schema for `shouldforget`: ```nolang { "" : { "result" : "", "proceed" : { "shouldForgetResult" : "", "shouldforget" : "" } } } ``` Example response schema for `social`: ```nolang { "" : { "result" : "", "proceed" : { "socialResult" : "", "social" : "" } } } ``` Example response schema for `solicit`: ```nolang { "" : { "result" : "", "proceed" : { "solicitResult" : "", "solicit" : "" } } } ``` Example response schema for `storepiielsewhere`: ```nolang { "" : { "result" : "", "proceed" : { "storePIIElsewhereResult" : "", "storepiielsewhere" : "" } } } ``` Example response schema for `track`: ```nolang { "" : { "result" : "", "proceed" : { "trackResult" : "", "track" : "" } } } ``` Example response schema for `web`: ```nolang { "" : { "result" : "", "proceed" : { "webResult" : "", "web" : "" } } } ``` ## Syntax **URI:** `/services/data/vXX.X/consent/action/action?ids=listOfIds` **Formats:** JSON **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** `None` **Request parameters** |Parameter|Description| |---------|-----------| |`action`|Required. The proposed action. If this parameter is used, `actions` can't be used.| |`aggregatedConsent`|Optional: true or false. `aggregatedConsent` is the same as `aggregatedConsent=true`. If true, one result is returned indicating whether to proceed or not, rather than a result for each ID. If any ID in the list returns false, the aggregated result is false.| |`datetime`|Optional. The timestamp for which consent is determined. The value is converted to the UTC timezone and must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). If not specified, defaults to the current date and time.| |`ids`|Required. Comma-separated list of IDs. The ID can be the record ID or the email address listed on the record.| |`policy`|Optional. Use `policy=requireExplicitConsent` to specify in the API response whether explicit consent was given for a contact point channel. The API returns an infoNotFound response when consent isn’t specified. This parameter is available in API version 49.0 and later.| |`purpose`|Optional. The reason for contacting a customer.| |`verbose`|Optional: true or false. `verbose` is the same as `verbose=true`. Verbose responses are slower than non-verbose responses. See the examples for a verbose response.| ## Example **Request for URI structure** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/action/track?ids=003xx000004TxyY,00Qxx00000syyO,003zz000004zzZ -H "Authorization: Bearer token" ``` **Request for Email addresses as IDs, specified purpose and timespan, and a verbose response** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/action/email?ids=j0t5t5b2@tkbxp5ia.com,4quxlswo@23wj7pwh.com&datetime=2018-12-12T00:00:00Z -H "Authorization: Bearer token" ``` **Response Body** ```nolang { "j0t5t5b2@tkbxp5ia.com" : { "result" : "Success", "proceed" : { "email" : "true" "emailResult" : "Success" }, "explanation" : [ { "objectConsulted" : "ContactTypePointConsent", "status" : "opt_in", "purpose" : "billing", "recordId" : "003xx000004TxyY", "value" : "true" },{ "objectConsulted" : "Contact", "field" : "HasOptedOutOfTracking", "recordId" : "1", "value" : "true" }] }, "4quxlswo@23wj7pwh.com" : { "result" : "Success", "proceed" : { "email" : "false" "emailResult" : "Success" }, "explanation" : [ { "objectConsulted" : "Contact", "field" : "HasOptedOutOfEmail", "recordId" : "00Qxx00000skwO", "value" : "true" } ] } } ``` # Compile Data for a Portability Request Aggregate your data subject's personally identifiable information (PII) into one file using the POST method of the Portability resource. The PII includes data found in the Account, Contact, Individual, Lead, Person, and User objects. You receive a response with a URL to download the file, a policy file ID, and information on the objects and fields you selected when creating the policy. Use the policy file ID to execute the Portability resource with the GET method. This resource is available in REST API version 50.0 and later. To use the Portability resource, you must have the ModifyAllData or PrivacyDataAccess user permission. Ensure that your Salesforce admin has granted you these permissions. ## Syntax **URI:** `/services/data/vXX.X/consent/dsr/rtp/execute` **Formats:** JSON **HTTP methods:** POST **Authentication:** `Authorization: Bearer token` **Request body** ```nolang { “dataSubjectId”:””, “policyName”:”” } ``` **Request parameters** |Parameter|Description| |---------|-----------| |`dataSubjectId`|The ID of the customer making the request. The ID is 15 or 18 characters long, and found in the Account, Contact, Individual, Lead, Person, and User objects.| |`policyName`|The name of an active policy. This contains the object in the dataSubjectId parameter.| ## Example **Example Request** ```nolang curl -X POST https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/dsr/rtp/execute -H "Authorization: Bearer token" -H "Content-Type: application/json" -d "@exampleRequestBody.json" ``` **Example Response Body** ```nolang { “status" : "SUCCESS", "warnings" : [ ], "result" : { "policyFileStatus" : "In Progress", "policyFileUrl" : "https://MyDomainName.my.salesforce.com/servlet/policyFileDownload?file=0jeS70000004CBO", "policyFileId" : "0jeS70000004CBO" } } ``` # Compile Multiple Types of Consent Settings Gets consent details based on multiple actions, like email and track, across specific consent management objects when the records have a lookup relationship. Available in API version 45.0 and later. To call Consent API, you must have either the View All Data or the Allow User Access to Privacy Data user permission. Requiring a perm ensures that the System Administrator gives explicit permission. This API accesses org-wide consent data, such as links between records and the value of consent flags, not just records to which the user ordinarily has access. Consent API gets consent details across the Contact, Contact Point Type Consent, Data Use Purpose, Individual, Lead, Person Account, and User objects when the records have a lookup relationship. The following table shows how the API responses are determined. If the consulted fields find conflicting consent preferences, the response returns the least permissive preference. For example, if Contact.HasOptedOutOfEmail is `false`, but Lead.HasOptedOutOfEmail is `true`, the response indicates that you can’t proceed with emailing the user. When you select *email* as the action, the API only aggregates consent for records that contain the same email address. If the record ID specified in the URI is associated with a record that contains a different email address, the consent settings of the associated record aren’t included in the API response. **note:** When the API compares consent settings across records, it doesn’t incorporate settings from converted leads. ||||| |-|-|-|-| |**Action**|**Fields Consulted**|**API Response**|**Response Schema**| |email|
  • Contact.HasOptedOutOfEmail
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
  • Lead.HasOptedOutOfEmail
  • PersonAccount.HasOptedOutOfEmail
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `email` after this table.| |fax|
  • Contact.HasOptedOutOfFax
  • DataUsePurpose.Name
  • Lead.HasOptedOutOfFax
  • PersonAccount.HasOptedOutOfFax
|Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Lead, or Person Account object exists.|See example response schema for `fax` after this table.| |geotrack|
  • DataUsePurpose.Name
  • Individual.HasOptedOutGeoTracking
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `geotrack` after this table.| |mail|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `mail` after this table.| |phone|
  • Contact.DoNotCall
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
  • Lead.DoNotCall
  • PersonAccount.DoNotCall
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `phone` after this table.| |portability|
  • DataUsePurpose.Name
  • Individual.SendIndividualData
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `portability` after this table.| |process|
  • DataUsePurpose.Name
  • Individual.HasOptedOutProcessing
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `process` after this table.| |profile|
  • DataUsePurpose.Name
  • Individual.HasOptedOutProfiling
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `profile` after this table.| |shouldforget|
  • DataUsePurpose.Name
  • Individual.ShouldForget
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `shouldforget` after this table.| |social|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `social` after this table.| |solicit|
  • DataUsePurpose.Name
  • Individual.HasOptedOutSolicit
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `solicit` after this table.| |storepiielsewhere|
  • DataUsePurpose.Name
  • Individual.CanStorePiiElsewhere
|Returns TRUE if the consulted field value is 1. Returns FALSE if the consulted field value is 0 or if no related Individual object exists.|See example response schema for `storepiielsewhere` after this table.| |track|
  • DataUsePurpose.Name
  • Individual.HasOptedOutTracking
|Returns TRUE if the consulted field value is 0. Returns FALSE if the consulted field value is 1 or if no related Individual object exists.|See example response schema for `track` after this table.| |web|
  • ContactPointTypeConsent.ContactPointType
  • ContactPointTypeConsent.EffectiveFrom
  • ContactPointTypeConsent.EffectiveTo
  • ContactPointTypeConsent.PrivacyConsentStatus
  • DataUsePurpose.Name
|Within the time range if specified in ContactPointTypeConsent: Returns TRUE if all consulted field values are 0. Returns FALSE if any consulted field value is 1 or if no related Contact, Contact Point Type Consent, Lead, or Person Account object exists.|See example response schema for `web` after this table.| Example response schema for `email`: ```nolang { "" : { "result" : "", "proceed" : { "emailResult" : "", email : “” } } } ``` Example response schema for `fax`: ```nolang { "" : { "result" : "", "proceed" : { "faxResult" : "", fax : "" } } } ``` Example response schema for `geotrack`: ```nolang { "" : { "result" : "", "proceed" : { "geotrackResult" : "", "geotrack" : "" } } } ``` Example response schema for `mail`: ```nolang { "" : { "result" : "", "proceed" : { "mailingResult" : "", "mail" : "" } } } ``` Example response schema for `phone`: ```nolang { "" : { "result" : "", "proceed" : { "phoneResult" : "", "phone" : "" } } } ``` Example response schema for `portability`: ```nolang { "" : { "result" : "", "proceed" : { "portabilityResult" : "", "portability" : "" } } } ``` Example response schema for `process`: ```nolang { "" : { "result" : "", "proceed" : { "processResult" : "", "process" : "" } } } ``` Example response schema for `profile`: ```nolang { "" : { "result" : "", "proceed" : { "profileResult" : "", "profile" : "" } } } ``` Example response schema for `shouldforget`: ```nolang { "" : { "result" : "", "proceed" : { "shouldForgetResult" : "", "shouldforget" : "" } } } ``` Example response schema for `social`: ```nolang { "" : { "result" : "", "proceed" : { "socialResult" : "", "social" : "" } } } ``` Example response schema for `solicit`: ```nolang { "" : { "result" : "", "proceed" : { "solicitResult" : "", "solicit" : "" } } } ``` Example response schema for `storepiielsewhere`: ```nolang { "" : { "result" : "", "proceed" : { "storePIIElsewhereResult" : "", "storepiielsewhere" : "" } } } ``` Example response schema for `track`: ```nolang { "" : { "result" : "", "proceed" : { "trackResult" : "", "track" : "" } } } ``` Example response schema for `web`: ```nolang { "" : { "result" : "", "proceed" : { "webResult" : "", "web" : "" } } } ``` ## Syntax **URI:** `/services/data/vXX.X/consent/multiaction?actions=listOfActions&ids=listOfIds` **Formats:** JSON **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** `None` **Request parameters** |Parameter|Description| |---------|-----------| |`actions`|Required. Comma-separated list of proposed actions. If this parameter is used, `action` can't be used.| |`aggregatedConsent`|Optional: true or false. `aggregatedConsent` is the same as `aggregatedConsent=true`. If true, one result is returned indicating whether to proceed or not, rather than a result for each ID. If any ID in the list returns false, the aggregated result is false.| |`datetime`|Optional. The timestamp for which consent is determined. The value is converted to the UTC timezone and must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). If not specified, defaults to the current date and time.| |`ids`|Required. Comma-separated list of IDs. The ID can be the record ID or the email address listed on the record.| |`policy`|Optional. Use `policy=requireExplicitConsent` to specify in the API response whether explicit consent was given for a contact point channel. The API returns an infoNotFound response when consent isn’t specified. This parameter is available in API version 49.0 and later.| |`purpose`|Optional. The reason for contacting a customer.| |`verbose`|Optional: true or false. `verbose` is the same as `verbose=true`. Verbose responses are slower than non-verbose responses. See the examples for a verbose response.| ## Example **Request for Multiaction URI structure** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/multiaction?actions=track,geotrack,email&ids=003xx000008TiyY,00Qxx00000skwO,dek65@tf7h.com -H "Authorization: Bearer token" ``` **Request for email addresses as IDs, specified purpose and timespan, and a verbose response** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/action/email?ids=j0t5t5b2@tkbxp5ia.com,4quxlswo@23wj7pwh.com&datetime=2018-12-12T00:00:00Z&purpose=billing&verbose=true -H "Authorization: Bearer token" ``` **Response Body** ```nolang { "j0t5t5b2@tkbxp5ia.com" : { "result" : "Success", "proceed" : { "email" : "false" "emailResult" : "Success" "track" : "false" "trackResult" : "Success" "solicit" : "false" "solicitResult" : "Success" }, "explanation" : [ { "objectConsulted" : "ContactTypePointConsent", "status" : "opt_in", "purpose" : "billing", "recordId" : "003xx000004TxyY", "value" : "true" },{ "objectConsulted" : "Individual", "field" : "HasOptedOutOfTracking", "recordId" : "0PKx000006JkyZ", "value" : "true" }] }, "4quxlswo@23wj7pwh.com" : { "result" : "Success", "proceed" : { "email" : "false" "emailResult" : "Success" "track" : "false" "trackResult" : "Success" "solicit" : "true" "solicitResult" : "Success" }, "explanation" : [ { "objectConsulted" : "Contact", "field" : "HasOptedOutOfEmail", "recordId" : "00Qxx00000skwO", "value" : "true" },{ "objectConsulted" : "Individual", "field" : "HasOptedOutOfSolicit", "recordId" : "0PKx000003JcpK", "value" : "false" }] } } ``` # Compile Visualforce Successfully Learn the requirements of compiling Visualforce pages and components. You can't save your Visualforce pages and components unless they correctly compile. Here's a list of things to watch out for when creating Visualforce pages: - Verify that your component tags start with the correct namespace identifier such as `apex:`—that is, `apex` followed by a colon. - Only Visualforce components and HTML elements are supported in API version 20.0 and later. Markup tags with other prefixes such as `soapenv` aren't supported. - Make sure that every opening quote and bracket has a closing one. - Verify that the controller or controller extension is named correctly. - Visualforce pages and components created using Salesforce API version 19.0 or higher must be written as well-formed XML. In general, this means that elements must be correctly nested, non-empty elements must have an end tag, empty elements must be terminated with a closing slash (“`/`”), and so on. The World Wide Web Consortium (W3C) provides [an article on the specifications of well-formed XML](http://www.w3.org/TR/xhtml1/#diffs). The following exceptions are allowed: - Code that violates well-formed XML is permitted inside JavaScript. For example, you don't need to use `` tags in Visualforce. - Code that violates well-formed XML is permitted inside expressions. For example, you don't need to escape quotation marks inside formulas. - XML directives that are normally required at the beginning of a page—such as ``—can occur inside top-level container tags, like `` and ``. # `compileAndTest()` Compile and test your Apex in a single call. ## Syntax ```java CompileAndTestResult[] = compileAndTest(CompileAndTestRequest request); ``` ## Usage Use this call to both compile and test the Apex you specify with a single call. Production organizations (not a Developer Edition or Sandbox Edition) must use this call instead of [`compileClasses()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileclasses.md) or [`compileTriggers()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compiletriggers.md). This call supports the [DebuggingHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-debuggingheader.md) and the [SessionHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-sessionheader.md). All specified tests must pass, otherwise data is not saved to the database. If this call is invoked in a production organization, the [RunTestsRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-request.md) property of the [CompileAndTestRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-request.md) is ignored, and all unit tests defined in the organization are run and must pass. ## Sample Code—Java Note that the following example sets `checkOnly` to `true` so that this class is compiled and tested, but the classes are not saved to the database. ```codesegment { CompileAndTestRequest request; CompileAndTestResult result = null; String triggerBody = "trigger t1 on Account (before insert){ " + " for(Account a:Trigger.new){ " + " a.description = 't1_UPDATE';}" + "}"; String testClassBody = "@isTest private class TestT1{" + " // Test for the trigger" + " public static testmethod void test1(){" + " Account a = new Account(name='TEST');" + " insert(a);" + " a = [select id,description from Account where id=:a.id];" + " System.assert(a.description.contains('t1_UPDATE'));" + " }" + " // Test for the class" + " public static testmethod void test2(){" + " String s = C1.method1();" + " System.assert(s=='HELLO');" + " }" + "}"; String classBody = "public class C1{" + " public static String s ='HELLO';" + " public static String method1(){" + " return(s);" + " }" + "}"; request = new CompileAndTestRequest(); request.setClasses(new String[]{classBody, testClassBody}); request.setTriggers(new String[]{triggerBody}); request.setCheckOnly(true); try { result = apexBinding.compileAndTest(request); } catch (RemoteException e) { System.out.println("An unexpected error occurred: " + e.getMessage()); } assert (result.isSuccess()); } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`request`|[CompileAndTestRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-request.md)|A request that includes the Apex and the values for any fields that need to be set for this request.| ## Response [CompileAndTestResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md) # CompileAndTestRequest The [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call contains this object, a request with information about the Apex to be compiled. A CompileAndTestRequest object has the following properties: |Name|Type|Description| |----|----|-----------| |`checkOnly`|boolean|If set to `true`, the Apex classes and triggers submitted are not saved to your organization, whether or not the code successfully compiles and unit tests pass.| |`classes`|string|Content of the class or classes to be compiled.| |`deleteClasses`|string|Name of the class or classes to be deleted.| |`deleteTriggers`|string|Name of the trigger or triggers to be deleted.| |`runTestsRequest`|[RunTestsRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-request.md)|Specifies information about the Apex to be tested. If this request is sent in a production organization, this property is ignored and all unit tests are run for your entire organization.| |`triggers`|string|Content of the trigger or triggers to be compiled.| Note the following about this object: - This object contains the [`RunTestsRequest`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-request.md) property. If the request is run in a production organization, the property is ignored and all tests are run. - If any errors occur during compile, delete, testing, or if the goal of 75% code coverage is missed, no classes or triggers are saved to your organization. This is the same requirement as Salesforce AppExchange package testing. - All triggers must have code coverage. If a trigger has no code coverage, no classes or triggers are saved to your organization. # CompileAndTestResult The [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call returns information about the compile and unit test run of the specified Apex, including whether it succeeded or failed. A CompileAndTestResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`classes`|[CompileClassResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)|Information about the success or failure of the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call if classes were being compiled.| |`deleteClasses`|[DeleteApexResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)|Information about the success or failure of the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call if classes were being deleted.| |`deleteTriggers`|[DeleteApexResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)|Information about the success or failure of the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call if triggers were being deleted.| |`runTestsResult`|[RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)|Information about the success or failure of the Apex unit tests, if any were specified.| |`success`|boolean|If `true`, all of the classes, triggers, and unit tests specified ran successfully. If any class, trigger, or unit test failed, the value is `false`, and details are reported in the corresponding result object:
  • [CompileClassResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)
  • [CompileTriggerResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)
  • [DeleteApexResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)
  • [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)
| |`triggers`|[CompileTriggerResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md)|Information about the success or failure of the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call if triggers were being compiled.| ## CompileClassResult This object is returned as part of a [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) or [`compileClasses()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileclasses.md) call. It contains information about whether or not the compile and run of the specified Apex was successful. A CompileClassResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`bodyCrc`|int|The CRC (cyclic redundancy check) of the class or trigger file.| |`column`|int|The column number where an error occurred, if one did.| |`id`|ID|An ID is created for each compiled class. The ID is unique within an organization.| |`line`|int|The line number where an error occurred, if one did.| |`name`|string|The name of the class.| |`problem`|string|The description of the problem if an error occurred.| |`success`|boolean|If `true`, the class or classes compiled successfully. If `false`, problems are specified in other properties of this object.| ## CompileTriggerResult This object is returned as part of a [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) or [`compileTriggers()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compiletriggers.md) call. It contains information about whether or not the compile and run of the specified Apex was successful. A CompileTriggerResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`bodyCrc`|int|The CRC (cyclic redundancy check) of the trigger file.| |`column`|int|The column where an error occurred, if one did.| |`id`|ID|An ID is created for each compiled trigger. The ID is unique within an organization.| |`line`|int|The line number where an error occurred, if one did.| |`name`|string|The name of the trigger.| |`problem`|string|The description of the problem if an error occurred.| |`success`|boolean|If `true`, all the specified triggers compiled and ran successfully. If the compilation or execution of any trigger fails, the value is `false`.| ## DeleteApexResult This object is returned when the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call returns information about the deletion of a class or trigger. A DeleteApexResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`id`|ID|ID of the deleted trigger or class. The ID is unique within an organization.| |`problem`|string|The description of the problem if an error occurred.| |`success`|boolean|If `true`, all the specified classes or triggers were deleted successfully. If any class or trigger is not deleted, the value is `false`.| # `compileClasses()` Compile your Apex in Developer Edition or sandbox organizations. ## Syntax ```java CompileClassResult[] = compileClasses(string[] classList); ``` ## Usage Use this call to compile Apex classes in Developer Edition or sandbox organizations. Production organizations must use [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md). This call supports the [DebuggingHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-debuggingheader.md) and the [SessionHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-sessionheader.md). ## Sample Code—Java ```codesegment public void compileClassesSample() { String p1 = "public class p1 {\n" + "public static Integer var1 = 0;\n" + "public static void methodA() {\n" + " var1 = 1;\n" + "}\n" + "public static void methodB() {\n" + " p2.MethodA();\n" + "}\n" + "}"; String p2 = "public class p2 {\n" + "public static Integer var1 = 0;\n" + "public static void methodA() {\n" + " var1 = 1;\n" + "}\n" + "public static void methodB() {\n" + " p1.MethodA();\n" + "}\n" + "}"; CompileClassResult[] r = new CompileClassResult[0]; try { r = apexBinding.compileClasses(new String[]{p1, p2}); } catch (RemoteException e) { System.out.println("An unexpected error occurred: " + e.getMessage()); } if (!r[0].isSuccess()) { System.out.println("Couldn't compile class p1 because: " + r[0].getProblem()); } if (!r[1].isSuccess()) { System.out.println("Couldn't compile class p2 because: " + r[1].getProblem()); } } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`scripts`|[string](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/primitive_data_types.htm#i1435116)|A request that includes the Apex classes and the values for any fields that need to be set for this request.| ## Response [CompileClassResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md) # `compileTriggers()` Compile your Apex triggers in Developer Edition or sandbox organizations. ## Syntax ```java CompileTriggerResult[] = compileTriggers(string[] triggerList); ``` ## Usage Use this call to compile the specified Apex triggers in your Developer Edition or sandbox organization. Production organizations must use [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md). This call supports the [DebuggingHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-debuggingheader.md) and the [SessionHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-sessionheader.md). ## Arguments |Name|Type|Description| |----|----|-----------| |`scripts`|[string](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/primitive_data_types.htm#i1435116)|A request that includes the Apex trigger or triggers and the values for any fields that need to be set for this request.| ## Response See [CompileTriggerResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-result.md). # Comply with a User’s Personal Information Visibility Settings Orgs with portals and sites provide specific settings to hide a user’s personally identifiable and contact information from other users. These settings aren’t enforced in Apex, even with Apex security features such as the `WITH USER_MODE` clause or the `stripInaccessible` method. To hide specific fields from a guest or external authenticated users, follow the sample code outlined below. **To hide a user’s personal information in the User object:** ```apex public User[] fetchUserDetail(Set userIds) { // Query all the fields of user which we are expected in user record to show that on UI or to // perform some business logic. User[] userRecords = [SELECT id, username, communitynickname, firstname, lastname, title FROM User WHERE id IN :userIds]; for (User userRecord : userRecords) { // User is not fetching his own record and is not standard user. if(userRecord.id != UserInfo.getUserId() && !Auth.CommunitiesUtil.isInternalUser()) { // clear-out all PII fields form user record which we have queried above. userRecord.username = ''; userRecord.title = ''; } } return userRecords; } ``` To comply with a user’s contact information visibility settings within a community or portal, we check the preferences associated with specific fields and show or hide the data accordingly. **For a user’s contact visibility settings within an Experience Cloud site:** ```apex public User[] fetchUserRecordRespectingFLVPreferences(Set userIds) { //Fetch users records along with fields specific user preferences. User[] userRecords = [SELECT email, UserPreferencesShowEmailToExternalUsers, UserPreferencesShowEmailToGuestUsers FROM User WHERE id IN :userIds]; // If context user is internal user then return result without any restriction. if (Auth.CommunitiesUtil.isInternalUser()) { return userRecords; } // If user is guest user then return result as per the user's UserPreference for the fields related to the Guest user visibility. if (Auth.CommunitiesUtil.isGuestUser()){ return fetchUserRecordForGuestUser(userRecords); } // Return result as per the user's UserPreference for the fields related to the External user visibility return fetchUserRecordForExternalUser(userRecords); } // Apply Field level visibilty logic by checking user's UserPreferences for the fields related to the External user visibility. public User[] fetchUserRecordForExternalUser(User[] userRecords) { for(User userRecord : userRecords) { //Clear field of user record when context user fetching other user's record and Field Level Visibility for that field is set to Restricted. if(userRecord.id != UserInfo.getUserId() && !userRecord.UserPreferencesShowEmailToExternalUsers) { userRecord.email = ''; } } return userRecords; } // Apply Field level visibilty logic by checking user's UserPreferences for the fields related to the Guest user visibility. public User[] fetchUserRecordForGuestUser(User[] userRecords) { for(User userRecord : userRecords) { //Clear field of user record when context user fetching other user's record and user preference for that field is NOT set to public. if(!userRecord.UserPreferencesShowEmailToGuestUsers) { userRecord.email = ''; } } return userRecords; } ``` **See Also** - [*Salesforce Help*: Manage Personal User Information Visibility for External Users](https://help.salesforce.com/s/articleView?id=platform.users_manage_personal_info_visibility.htm&type=5) - [*Salesforce Help*: Share Personal Contact Information Within Experience Cloud Sites](https://help.salesforce.com/s/articleView?id=platform.networks_contact_info_visibility.htm&type=5) # Component `Component` contains methods to work with components. ## Methods - **[addEventHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addeventhandler.md)** Dynamically adds an event handler for a component or application event. - **[addHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addhandler.md)** Deprecated. Use `addEventHandler()` instead. - **[addValueHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addvaluehandler.md)** Adds handlers to values owned by the component. - **[addValueProvider()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addvalueprovider.md)** Adds custom value providers to a component. - **[autoDestroy()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-autodestroy.md)** Sets a flag to tell the rendering service whether or not to destroy this component when it is removed from its rendering facet. - **[clearReference()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-clearreference.md)** Clears a live reference for the value passed in using property syntax. For example, if you use `aura:set` to set a value and later want to reset the value using `component.set()`, clear the reference before resetting the value. - **[destroy()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-destroy.md)** Destroys the component and cleans up memory. After a component that is declared in markup is no longer in use, the framework automatically destroys it and frees up its memory. If you create a component dynamically in JavaScript and that component isn't added to a facet (`v.body` or another attribute of type `Aura.Component[]`), you have to destroy it manually using `destroy()` to avoid memory leaks. - **[find()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-find.md)** Locates a component using its local ID (`aura:id`). - **[get()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-get.md)** Returns the value referenced using property syntax. For example, `cmp.get("v.attr")` returns the value of the `attr` attribute. - **[getConcreteComponent()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getconcretecomponent.md)** Gets the concrete implementation of a component. If the component is concrete, the method returns the component itself. For example, call this method to get the concrete component of a super component. - **[getElement()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getelement.md)** If the component renders only a single element, return it. Otherwise, use `getElements()`. - **[getElements()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getelements.md)** Returns a map of the elements rendered by the component. - **[getEvent()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getevent.md)** Returns a new event instance of the named component event. - **[getGlobalId()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getglobalid.md)** Gets the global ID, which is the generated globally unique id of the component. It can be used to locate the instance later, but will change across page loads. - **[getLocalId()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getlocalid.md)** Gets the ID set using the `aura:id` attribute. Pass the local ID into `find()` on the parent component to locate this child component. - **[getName()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getname.md)** Returns the component’s code-compatible camel case name, such as `'lightningButton'`. - **[getReference()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getreference.md)** Returns a live reference to the value indicated using property syntax. This method is useful when you dynamically create a component. - **[getSuper()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getsuper.md)** Returns the super component. - **[getType()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-gettype.md)** Returns the component’s canonical type; for example, `'lightning:button'`. - **[getVersion()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-getversion.md)** Returns the component’s version number. - **[isConcrete()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-isconcrete.md)** Returns `true` if the component is concrete, or `false` otherwise. A concrete component is a sub-component in an inheritance chain. - **[isInstanceOf()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-isinstanceof.md)** Checks whether a component is an instance of the given component or interface name. - **[isValid()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-isvalid.md)** Returns `true` if the component has not been destroyed. - **[removeEventHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-removeeventhandler.md)** Dynamically removes a component event handler for the specified event. - **[set()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-set.md)** Sets the value referenced using property syntax. # Component Access Control The `access` attribute on the `aura:component` tag controls whether the component can be used outside of the component’s namespace. Possible values are listed below. |Modifier|Description| |--------|-----------| |`public`|Available within your org only. This is the default access value.| |`global`|Available in all orgs.| **note:** Components aren’t directly addressable via a URL. To check your component output, embed your component in a `.app` resource. # Component Attributes Component attributes are like member variables on a class in Apex. They are typed fields that are set on a specific instance of a component, and can be referenced from within the component's markup using an expression syntax. Attributes enable you to make components more dynamic. Use the `` tag to add an attribute to the component or app. Let’s look at the following sample, `helloAttributes.app`: ```nolang Hello {!v.whom}! ``` All attributes have a name and a type. Attributes may be marked as required by specifying `required="true"`, and may also specify a default value. In this case we've got an attribute named `whom` of type String. If no value is specified, it defaults to "world". Though not a strict requirement, `` tags are usually the first things listed in a component’s markup, as it provides an easy way to read the component's shape at a glance. ## Attribute Naming Rules An attribute name must follow these naming rules: - Must begin with a letter or an underscore - Must contain only alphanumeric or underscore characters ## Expressions `helloAttributes.app` contains an expression, `{!v.whom}`, which is responsible for the component's dynamic output. `{!expression}` is the framework's expression syntax. In this case, the expression we are evaluating is `v.whom`. The name of the attribute we defined is `whom`, while `v` is the value provider for a component's attribute set, which represents the view. **note:** Expressions are case sensitive. For example, if you have a custom field `myNamespace__Amount__c`, you must refer to it as `{!v.myObject.myNamespace__Amount__c}`. - **[Supported aura:attribute Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-aura-attribute.md)** `aura:attribute` describes an attribute available on an app, interface, component, or event. - **[Basic Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-basic.md)** - **[Function Type](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-function.md)** An attribute of an `aura:method` can have a type corresponding to a JavaScript function so that you can pass a function into the method. An attribute of a component can’t have a type corresponding to a JavaScript function. - **[Object Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-object.md)** - **[Standard and Custom Object Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-object-salesforce.md)** - **[Collection Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-collection.md)** - **[Custom Apex Class Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-apex.md)** An Aura component attribute type can correspond to values held in an Apex class. An attribute type can be a custom Apex class, a List standard Apex class, or a Map standard Apex class. To use values held in other standard Apex classes, first create a custom Apex class, and then copy the needed values from instances of the standard class into your custom class. - **[Framework-Specific Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-attr-types-aura.md)** **See Also** - [Supported aura:attribute Types](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-aura-attribute.md) - [Using Expressions](https://developer.salesforce.com/docs/platform/aura-platform/expr/expr-overview.md) # Component Behavior When Rendered as PDF Understanding how Visualforce components behave when converted to PDF is essential to creating pages that render well. The Visualforce PDF rendering service renders static HTML and basic CSS that is explicitly provided by the page. As a rule, don’t use components that: - Rely on JavaScript to perform an action - Depend on Salesforce style sheets - Use assets such as style sheets or graphics that aren’t available in the page itself or in a static resource To check if your Visualforce page falls into one of these categories, right-click anywhere on the page and view the HTML source. If you see a ` ``` Override a page-level timeout configuration on a per-request basis by setting the timeout in the configuration object for that request, as described above. # Confirm Sales Meeting Confirms a meeting time that's part of a request to get available meeting time slots. Salesforce Inbox must be enabled in your org. This object is available in API version 66.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/vXX.X/actions/standard/confirmSalesMeeting` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`meetingRequestId`|string|Required. The ID of the meeting request associated with a Get Available Meeting Times request.| |`meetingTime`|string|Required. The meeting time in epoch milliseconds corresponding to the selected start time.| ## Outputs |Output|Type|Description| |------|----|-----------| |`meetingStatus`|string|The status of the meeting scheduling attempt.| |`outputErrorCode`|string|The error code returned by the Confirm Sales Meeting action.| |`outputErrorMessage`|string|The error message returned by the Confirm Sales Meeting action.| ## Usage **Sample Input** ```apex { "inputs": [ { "meetingRequestId": "0MRXX00000001ABCDE", "meetingTime": "1752566400000" } ] } ``` **Sample Output** ```apex { "outputs": [ { "meetingStatus": "Success" } ] } ``` **note:** If an error occurs, the output includes `outputErrorCode` and `outputErrorMessage` fields instead of `meetingStatus`. For more information about this invocable action, see [Sales | Return Calendar Link](https://help.salesforce.com/s/articleView?id=ai.agent_ref_return_calendar_link.htm) and [Sales | Send Meeting Request](https://help.salesforce.com/s/articleView?id=ai.copilot_actions_ref_send_meeting_request.htm&) in the Agentforce Standard Action Reference and [Flow Core Actions: Generate Sales Meeting Link Action](https://help.salesforce.com/s/articleView?id=platform.automate_flow_ref_elements_actions_generate_sales_meeting_link.htm) in Salesforce Help. # Connect REST API Limits Limits protect shared resources. These limits are for Connect REST API consumers. Most Connect REST API requests are subject to the same rate limits as other Salesforce APIs. Only requests to Chatter REST API resources (a subset of Connect REST API resources) are subject to a per user, per application, per hour rate limit. When you exceed the rate limit, Connect REST API resources return a 503 Service Unavailable error code. For applications using a session ID from Salesforce, the rate limit is per user, per hour—there isn’t a separate bucket for applications. All applications the user accesses with a session ID use this general quota. To take advantage of the per user, per application, per hour limit, use OAuth tokens. **note:** Load, performance, and other system issues can prevent some limits from being reached. Limits can change without notice. Ensure that your applications make efficient use of available requests and gracefully handle the 503 error code. # Connecting to the API The first portion of any JavaScript code that uses the AJAX Toolkit must make the toolkit available to the JavaScript code. The syntax for this is different depending on whether you are embedding JavaScript in a Visualforce page, or a button or link. **note:** API calls using the AJAX Toolkit always use the latest version of installed packages. If you're working with Visualforce components, keep in mind that you cannot access deleted components from previous package versions using the API. For Visualforce pages or any source other than a custom `onclick` JavaScript button, specify a `
``` For Visualforce pages where ``, you must first set `var __sfdcSiteUrlPrefix = '{!$Site.Prefix}'` before you load the toolkit file: ```html ``` Alternatively, you can set the site path directly on the `UserContext` JavaScript object with `UserContext.siteUrlPrefix = '{!$Site.Prefix}';`. For a custom `onclick` JavaScript button, use `!requireScript` to point to the toolkit file: ```html {!requireScript("/soap/ajax/68.0/connection.js")} ... ``` The AJAX Toolkit picks up the endpoint and manages the session ID. You do not need to set them. The version of the AJAX Toolkit is in the URL. After this script executes, the toolkit is loaded and a global object, `sforce.connection`, is created. This object contains all of the API calls and AJAX Toolkit methods, and manages the session ID. No other session management is needed. Salesforce checks the IP address from which the client app is logging in and blocks logins from unknown IP addresses. For a blocked login via the API, Salesforce returns a login fault. Then, the user must add their security token to the end of their password in order to log in. A security token is an automatically-generated key from Salesforce. For example, if a user's password is `mypassword`, and their security token is `XXXXXXXXXX`, then the user must enter `mypasswordXXXXXXXXXX` to log in. Users can obtain their security token by changing their password or resetting their security token via the Salesforce user interface. When a user changes their password or resets their security token, Salesforce sends a new security token to the email address on the user's Salesforce record. The security token is valid until a user resets their security token, changes their password, or has their password reset. When the security token is invalid, the user must repeat the login process to log in. To avoid this, the administrator can make sure the client's IP address is added to the organization's list of trusted IP addresses. For more information, see “Security Token” in the in the [SOAP API Developer Guide](https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/apex_api.pdf). We recommend that you obtain your security token via the Salesforce user interface from a trusted network prior to attempting to access Salesforce from a new location. If single sign-on (SSO) is enabled, users who access the API or a desktop client can't log in unless their IP address is included on your org's list of trusted IP addresses or on their profile, if their profile has IP address restrictions set. The delegated authentication authority usually handles login lockout policies for users with the Uses Single Sign-On permission. However, if the security token is enabled, your login lockout settings determine how many times a user can try to log in with an invalid security token before getting locked out. For more information, see Setting Login Restrictions and Setting Password Policies in Salesforce Help. # Consent Your users can store consent preferences in different locations and possibly inconsistently. You can locate your customers’ preferences for consent across multiple records when using API version 44.0 and later. Tracking consent preferences helps you and your users respect the most restrictive requests. You can use the Consent API with specific Data Cloud parameters with API version 50.0 and later. # Consent Write Your users can store consent preferences in different locations. The Consent Write API can update and write consent across multiple records through a single API call, helping you sync consent across records or populate the new Consent data model. This resource is available in REST API version 48.0 and later. **note:** The response for Consent API requests can include a 200 status code even if errors are returned. Consent API writes consent values across the Contact, Contact Point Type Consent, Data Use Purpose, Individual, Lead, Person Account, and User objects when the records have a lookup relationship or share an email address. This API can also write to the Data Cloud Individual record. The Consent API can't locate records in which the email address field is protected by Platform Encryption. **note:** For the Spring ‘21 release, the API only takes in a single email address. Any record with a matching email address is updated based on the parameters set in the API call. All records with the email address listed are updated. If the Create Individual parameter is selected and no Individual record exists, the API creates an Individual record. If warranted, the API also creates a Contact Point Type Consent and Contact Point Email record. If you aren’t passing anything in the request body, pass in an empty object {}. ## Syntax **URI:** `/services/data/vXX.X/consent/action/action?ids=listOfIds` **Formats:** JSON **HTTP methods:** PATCH **Authentication:** `Authorization: Bearer token` **Request parameters** |Parameter|Description| |---------|-----------| |`blobParam`|Optional. Use to pass information to Data Cloud, such as portability write location. Use only for `mode=cdp`. This parameter must be passed in as part of the PATCH request body.| |`captureDate`|Optional. The date and time when consent is captured. The default is the date and time that the API call is made.| |`captureContactPointType`|Optional. Describes how consent is captured (web, phone, email). Supported values are `email`, `phone`, or `web` (default).| |`captureSource`|Optional. The source through which consent is captured. The default capture source is Consent API. Max length 255 characters.| |`consentName`|Optional. Use to set the name for any new consent records. Default is: `Individual Name-Datetime ( 2019-03-31T15:47:57). ` Max length is 255 characters.| |`createIndividual`|Optional. Boolean. If set to `true` and the API call includes an email address that matches multiple records without an Individual object, then an Individual object is created. Any consent records with an email address that match the email in the API call are linked to the new Individual object. If multiple records are found, then any records not linked to an Individual object is linked to the Individual object found in the other records. If more than one Individual object is found on the matching records, then the call is rejected.| |`doubleOptIn`|Optional. The date and time that the double opt-in is completed, formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md).| |`effectiveFrom`|Optional. The date from which consent is effective, formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). The default is the date that the API call is made.| |`effectiveTo`|Optional. The date through which consent is effective, formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md).| |`ids`|Required. The email address used to sync consent. The ID can be the record ID or the email address listed on the record. You can pass up to 1,000 IDs in the request body. When `mode=cdp`, the ID value is a string equal to the Individual ID attribute.| |`individualName`|Optional. The name of the person in an Individual record. If a name isn’t provided for a new Individual record, then the local part of the passed-in email address is used. Max length is 80 characters.| |`mode`|Optional. Default is `normal`. The allowed modes are: `normal` or `cdp`. With `mode=cdp`, the request is passed to the Data Cloud platform to get or write consent. The `mode=cdp` parameter only supports the `action`, `blobParam`, and `ids` parameters.| |`purposeName`|Optional. The data use purpose for which consent is provided. Must use an existing data use purpose that you previously created. If more than one purpose with the same name exists, only one purpose is selected.| |`status`|Required. Status of the consent (`OptIn`, `OptOut`, `Seen`, `NotSeen`.) If action exists on an Individual object (for example, tracking or processing), the only valid values are `OptIn` and `OptOut`.| **Action** Allowed values are: - email - fax - geotrack - mailing - phone - portability - process - profile - shouldForget - social - solicit - storePiiElsewhere - track - web ## Security To call the Consent Write API, you must have either the ModifyAllData or the ConsentApiUpdate user permission. This API writes org-wide consent data, such as links between records and the value of consent flags, and not just records to which the user ordinarily has access. The ConsentApiUpdate user permission grants full write permission to the user during the Consent Write API call. ## Example **Example Request** ```nolang curl -X PATCH https://MyDomainName.my.salesforce.com/services/data/v68.0/consent/action/?ids=&status=&createIndividual= -H "Content-Type: application/json" -d "@exampleRequestBody.json" ``` **Example Request Body** **note:** Passing in IDs through the request body allows up to 1,000 IDs to be included. ```nolang { "ids": [ "001ZM000002ZhpHYAS", "001ZM000002ZhpFYAS" ] } ``` **Example Response Body** ```nolang { "" : { "result" : "Success", "edited" : [{ "objectType" : "", "field" : "", "valueOfField" : "", "id" : "" }], } } ``` # ConsentEvent Notifies subscribers of changes to consent fields or contact information on all core objects. This object is available in API version 50.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/ConsentEvent` ## Special Access Rules Users with ReadAllData or PrivacyDataAccess permissions have read access. ## Event Delivery Allocation Enforced Yes ## Fields ### `AssociatedIds` **Type:** string **Properties:** Nillable **Description:** A list of IDs associated with the changed record. Possible IDs are: Possible values: - `globalPartyId` - `individual` - `lead` - `contact` - `personAccount` - `user` - `contactPoint` - `contactPointConsent` - `contactPointTypeConsent` ### `ChangeInitiator` **Type:** string **Properties:** Nillable **Description:** The ID of the user who changed the record. ### `ChangeTimestamp` **Type:** dateTime **Properties:** Nillable **Description:** Indicates the date and time the change event occurred. ### `ChangeType` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** Indicates the type of change made to the record. Possible values are `Create`, `Delete`, `Undelete`, `Unknown`, or `Update`. ### `ConsentCaptureSource` **Type:** string **Properties:** Nillable **Description:** Indicates how consent was captured. For example, if the ConsentCaptureType is a website, the ConsentCaptureSource is the website URL. ### `ConsentCaptureType` **Type:** string **Properties:** Nillable **Description:** Indicates the type of source consent was captured through. For example, a website or online form. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `NewValues` **Type:** string **Properties:** Nillable **Description:** Indicates new values that were added to the object, if relevant. ### `ObjectName` **Type:** string **Properties:** Nillable **Description:** The name of the object for which the change event was captured. ### `RecordId` **Type:** string **Properties:** Nillable **Description:** The ID of the record that was changed. ### `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. # ConsentUnsubscribeAllEvent Notifies subscribers when a user unsubscribes from all communications on a preference form created in Preference Manager. This object is available in API version 60.0 and later. ## Supported Calls `create()`, `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/ConsentUnsubscribeAllEvent` ## Event Delivery Allocation Enforced Yes ## Special Access Rules This object is available for users with the Privacy Center license and the Manage Preference Manager user permission. ## Fields ### `EventDetails` **Type:** textarea **Properties:** Create **Description:** JSON text that contains the details for the unsubscribe all event, such as the timestamp for when the event happened. ### `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. # Considerations Lightning Data Service is powerful and simple to use. However, it’s not a complete replacement for writing your own data access code. Here are some considerations to keep in mind when using it. Lightning Data Service is available in the following containers: - Lightning Experience - Salesforce app - Experience Builder sites - Lightning Out - Lightning Components for Visualforce - Standalone Lightning apps - Lightning for Gmail - Lightning for Outlook Lightning Data Service supports primitive DML operations—create, read, update, and delete. It operates on one record at a time, which you retrieve or modify using the record ID. Lightning Data Service supports spanned fields with a maximum depth of five levels. Support for working with collections of records or for querying for a record by anything other than the record ID isn’t available. If you must support higher-level operations or multiple operations in one transaction, use standard `@AuraEnabled` Apex methods. Lightning Data Service shared data storage provides notifications to all components that use a record whenever a component changes that record. It doesn’t notify components if that record is changed on the server, for example, if someone else modifies it. Records changed on the server aren’t updated locally until they’re reloaded. Lightning Data Service notifies listeners about data changes only if the changed fields are the same as in the listener’s fields or layout. Lightning Data Service does a lot of work to make code perform well. - Loads record data progressively. - Caches results on the client. - Invalidates cache entries when dependent Salesforce data and metadata changes. - Optimizes server calls by bulkifying and deduping requests. ## Use Base Components To work with record data, use the following base components. - `lightning:recordForm` - `lightning:recordEditForm` - `lightning:recordViewForm` Use these base components to: - Create a metadata-driven UI or form-based UI similar to the record detail page in Salesforce. - Display record values based on the field metadata. - Display or hide localized field labels. - Display the help text on a custom field. - Perform client-side validation and enforce validation rules. Alternatively, use `force:recordData` to: - Create your own custom UI - Return raw record data for a small number of fields - Create UI that’s not metadata-driven When using `force:recordData`, load the data once and pass it to child components as attributes. This approach reduces the number of listeners and minimizes server calls, which improves performance and ensures that your components show consistent data. For more information, see the [force:recordData documentation](https://developer.salesforce.com/docs/component-library/bundle/force:recordData/documentation). For examples of base components in action, see [Lightning Action Examples](https://developer.salesforce.com/docs/platform/aura-platform/guide/data-service-example.md). The base components and `force:recordData` are built on Lightning Data Service. If Lightning Data Service detects a change to a record or any data or metadata it supports, the components receive the new value. The detection is triggered if: - An Aura or Lightning web component mutates the record. - The Lightning Data Service cache entry expires and then a component built on Lightning Data Service triggers a read. The cache entry and the Lightning web component must be in the same browser and app (for example Lightning Experience) for the same user. **note:** To improve performance, we recommend specifying the fields you need instead of using a layout. Use a layout only if you want the administrator, not the component, to control the fields that are provisioned. The component must handle receiving every field that is assigned to the layout for the context user. For more information, see [Page Layouts](https://help.salesforce.com/articleView?id=customize_layout.htm) in Salesforce Help. ## Supported Objects Lightning Data Service supports custom objects and the [standard objects](https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_get_started_supported_objects.htm) that User Interface API supports. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the AppReviewService API. **Development Considerations** You can develop the user experience for your component on a desktop or laptop development system. Be sure to test app review functionality on the physical devices on which you plan to deploy your Lightning app. Apple and Google provide their own tips and best practices for requesting app reviews. - iOS: [Requesting App Store reviews (Apple)](https://developer.apple.com/documentation/storekit/requesting_app_store_reviews) - iOS: [Ratings, Reviews, and Responses](https://developer.apple.com/app-store/ratings-and-reviews/) - Android: [Google Play In-App Reviews API (Google)](https://developer.android.com/guide/playcore/in-app-review) **Testing Limitations** **iOS** When you test app review features while your app is in development mode, the app rating and review request view is displayed so you can test the UI experience. If you're testing app reviews on an app that you distribute through TestFlight, it won't display the app rating and review request. **Android** You can test the app review integration without publishing your app to production using either internal test tracks or internal app sharing. - [Test using an internal test track (Google)](https://developer.android.com/guide/playcore/in-app-review/test#internal-test-track) - [Test using internal app sharing (Google)](https://developer.android.com/guide/playcore/in-app-review/test#internal-app-sharing) As you test your app review features on Android, you might encounter issues. To learn about some common issues with reviews on Google Play and their solutions, see [Troubleshooting (Google)](https://developer.android.com/guide/playcore/in-app-review/test#troubleshooting). **Publisher Playground App** While testing app review features isn’t available on the Publisher Playground app, you can test it using Playground app virtual device builds. - [Playground App Virtual Device Builds (Salesforce)](https://help.salesforce.com/s/articleView?id=xcloud.s1_branded_apps_playground_app_simulator.htm&type=5) **Device Limitations** AppReviewService doesn’t implement an app review feature itself. Instead, it makes available the native features of the underlying platform (Android or iOS). While the features provided by AppReviewService are the same across both, it’s subject to platform-specific quirks and minor differences. **AppReviewService Considerations** Be aware of the following considerations when using AppReviewService in your Lightning app. - AppReviewService is built on top of mobile operating system and device features. AppReviewService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of AppReviewService can change without notice. - A Lightning component that uses AppReviewService can have a custom user interface in the component itself. # Considerations and Limitations Keep the following in mind when developing features that use the BarcodeScanner API. **Device Limitations** - BarcodeScanner requires the use of a mobile device camera. The user must grant your app access to the camera. The platform governs the exact user experience. The request happens automatically on first use, and is managed by the device itself. However, you can plan for it when designing the user experience of your app. - BarcodeScanner doesn’t implement scanning itself. Instead, it makes available the scanning feature of the underlying platform (Android or iOS). While the features provided by BarcodeScanner are the same across both platforms, it _is_ subject to some platform-specific quirks and minor differences. - The scanner can't recognize the barcode if you can’t get a clear picture of it. The quality of the device camera affects barcode recognition. A damaged or low-quality camera lens or focusing system, poor lighting, motion, and other factors can make it difficult to get a clear picture of a barcode. - The quality of the barcode affects barcode recognition. Specifically, damaged or obscured barcodes are hard to recognize successfully. - If you’re having trouble getting BarcodeScanner to recognize a barcode: - First, verify that the barcode type is one of the [supported barcode symbologies](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-compatibility.md). There are other barcode types that aren’t supported. - Second, verify that you’ve configured BarcodeScanner to recognize the expected symbology. See `BarcodeScannerOptions` in [BarcodeScanner Data Types](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-barcodescanner-data-types.html) for configuration details. - Finally, check whether another app on the same device is able to recognize the barcode. If the standard camera app on the device can’t recognize the barcode, neither can BarcodeScanner. **Development Considerations** - BarcodeScanner requires access to camera hardware. To test scanning during development, use actual, physical devices. - The Android emulator can simulate camera hardware by using a webcam on your development system. To do so, edit the camera configuration for your Android Virtual Device, in the advanced settings panel. However, the camera built into most laptops is much lower quality than what’s found on modern mobile phones. A low-quality camera limits the usefulness of testing barcode recognition. - The iOS simulator doesn’t provide access to simulated camera hardware at all. You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test scanning functionality on the physical devices on which you plan to deploy your Lightning app. **Usage Considerations** Keep in mind these considerations to increase the chances of ‌performing a successful scan. - Barcode scanning is functional only in portrait orientation, not in landscape orientation. - Device camera quality significantly impacts barcode scanning success. High-end devices with better cameras scan barcodes more accurately and efficiently than low-end devices, which are more likely to make mistakes in finding them. - For optimal scanner performance, make sure that barcodes are printed on a flat surface, not a curved, or deformed one. - Scanning barcodes from digital screens can be challenging due to minor image artifacts introduced by the screen when viewed through a device’s camera lens. This is a common issue when aiming a camera at a digital display, making digital screen scanning inherently more difficult. - Scanning becomes more challenging when barcodes are resized or scaled down to fit a smaller area (such as a digital screen), especially long variable-length barcodes. - When scanning a small barcode, bring your phone as close as possible without blurring the image. Blurring reduces the chances of a successful scan. You can also pinch-to-zoom on the scanner viewport to enlarge the image. - Prioritize moving the phone closer to the barcode before using pinch-to-zoom. Many devices, especially older Android models, use digital zoom for pinch-to-zoom, particularly at higher zoom levels. This can significantly reduce image quality. - On Apple Pro and Pro MAX series devices, the Nimbus BarcodeScanner uses the ultra-wide angle lens for macro-mode shooting when the phone is positioned physically closer to a barcode. This automatic lens switch enables successful scans even at close distances by preventing blurry images. This feature isn’t available for Android devices. **BarcodeScanner Considerations** Be aware of the these considerations when using BarcodeScanner in your Lightning app. - BarcodeScanner is built on top of mobile operating system features. BarcodeScanner’s scanning capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of BarcodeScanner can change without notice. - BarcodeScanner provides haptic feedback (a short vibration) after a successful scan on iOS devices. There’s no haptic feedback on Android devices. - The Nimbus BarcodeScanner plugin can behave differently on iOS and Android, because of the differences in their operating systems and how their barcode scanning APIs work. - Third-party barcode scanning apps often use their own scanning and detection tools and libraries to scan barcodes. These tools can differ from the built-in operating system (Android and iOS) APIs used by the Nimbus BarcodeScanner. - BarcodeScanner performs better with 2D barcodes (such as QR codes) due to their lower error susceptibility during detection. In contrast, "linear" or 1D barcodes (such as Code128, UPC) are more prone to detection errors. Furthermore, some 1D barcodes have variable data lengths. This can lead to partial payload scans, as the scanner might mistakenly register a complete barcode even when only a portion is visible. Therefore, if you have the option, 2D barcodes are preferable. To improve handling of 1D barcodes, you can configure the scanner by setting `manualConfirmation=true` in the [BarcodeScanner options](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-barcodescanner-data-types.html#barcodescanneroptions). This setting requires the user to confirm the detected barcode by tapping a screen button, allowing time to bring the entire barcode into view. - BarcodeScanner uses OS-level APIs for barcode processing, particularly 1D barcodes that may contain special characters. It doesn’t filter or process these characters. Instead, whatever is detected by the APIs is returned to the LWC as-is. This approach maintains the scanner's generic utility, catering to diverse customer needs where special characters in the payload are desired. Therefore, any subsequent filtering or processing of special characters is the developer's responsibility. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the BiometricsService API. **Device Limitations** BiometricsService doesn’t manage biometrics data and checking itself. Instead, it makes available certain biometrics capabilities of the underlying platform (Android or iOS) and hardware (phone or other mobile device). While the features provided by BiometricsService are the same across both platforms, they’re subject to some platform-specific quirks and minor differences. **Development Considerations** You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test biometrics functionality on the physical devices on which you plan to deploy your Lightning app. **BiometricsService Considerations** BiometricsService is built on top of mobile operating system and device features. BiometricsService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of BiometricsService can change without notice. # Considerations and Limitations Keep the following in mind when developing features that use the CalendarService API. **Device Limitations** CalendarService doesn’t manage calendar and event data itself. Instead, it makes available certain calendar and event data of the underlying platform (Android or iOS) and hardware (phone or other mobile device). While the features provided by CalendarService are the same across both platforms, they’re subject to some platform-specific quirks and minor differences. - In order for CalendarService to access a calendar and perform associated actions, the account associated with a calendar must be synced to the device and grant the device permission to access the calendar. For example, if a user has an email account synced to their device but has not granted the device access to that account’s calendar, CalendarService won’t be able to interact with that calendar. - Some devices have other restrictions, such as an employer-managed MDM, that limit access to certain device calendar APIs. Such restrictions can prohibit CalendarService from accessing and interacting with these calendars. - CalendarService requires the use of the mobile device’s calendar. Your user must grant your app access to the calendar. The exact user experience is governed by the platform. The request happens automatically on first use, and is managed by the device itself, but you should plan for it when designing the user experience of your app. - In Android 11 or later, if the user taps “Deny” for permission to access the Calendar app more than once during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. In previous versions of Android, users would see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have chosen to deny. If the user has denied permission to access the Calendar app and needs to change their permissions to allow access, they can do so in their device’s settings. **Development Considerations** You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test calendar and event functionality on the physical devices on which you plan to deploy your Lightning app. **important:** CalendarService allows for actions that, if used irresponsibly or incorrectly, can lead to irreversible consequences on your users’ devices. These **dangerous actions** include altering and deleting calendar events. As with all mobile capabilities, implementation of CalendarService’s functionality, dangerous actions included, is at your discretion. Use caution when using dangerous actions in your component. **CalendarService Considerations** CalendarService is built on top of mobile operating system and device features. CalendarService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of CalendarService can change without notice. # Considerations and Limitations Keep the following in mind when developing features that use the ContactsService API. **Device Limitations** ContactsService doesn’t manage contact information itself. Instead, it makes available certain contact data of the underlying platform (Android or iOS) and hardware (phone or other mobile device). While the features provided by ContactsService are the same across both platforms, they’re subject to some platform-specific quirks and minor differences. - The user interface for selecting contacts are subject to differences between platforms. For example, the **Done** button on iOS vs. a checkmark icon on Android, and differences in cancellation: ![UX of Android contact selection](https://developer.salesforce.com/media/mobile-offline/contactsservice_android_ux.png) ![UX of iOS contact selection](https://developer.salesforce.com/media/mobile-offline/contactsservice_ios_ux.png) - ContactsService requires the use of the mobile device’s contacts. Your user must grant your app access to contacts. The exact user experience is governed by the platform. The request happens automatically on first use, and is managed by the device itself, but you should plan for it when designing the user experience of your app. - In Android 11 or later, if the user taps “Deny” for permission to access the Contacts app more than once during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. In previous versions of Android, users would see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have chosen to deny. If the user has denied permission to access the Contacts app and needs to change their permissions to allow access, they can do so in their device’s settings. - If Mobile Device Management (MDM) is in use on a device, and MDM restricts access to contacts data, ContactsService can’t access it. - If the user doesn't have any contacts in their device’s contact list, ContactsService won’t work. - If the user has contacts associated with specific accounts on their device, those accounts must have contacts sync enabled in order for ContactsService to access them. In other words, ContactsService can only access contacts that are visible in your user’s device’s native contact list. See [Use other contact accounts on iPhone](https://support.apple.com/guide/iphone/use-other-contact-accounts-iph14a87326/ios) (iOS) and [Back up & sync device contacts](https://support.google.com/contacts/answer/9423168?hl=en&ref_topic=9160153) (Android) for more information. If you’re having trouble getting ContactsService to access contact data, try the following: - First, verify that your device contact list contains the contact data you’re trying to access. ContactsService can only access contacts that are visible in your device’s native contact list. - Next, verify that you’ve granted contacts permission to the mobile app where your component is running. You can check this in your device’s settings. - Finally, double-check the configuration of ContactsService in your code. **Development Considerations** Virtual devices might not have any contact data when they’re created. To test ContactsService on a virtual device, you’ll first need to create some contact records in the virtual device’s Contacts app. Alternatively, you can import contact data in the standard .vcf format, or sign into a real Google or iCloud account that has contact data associated with it. You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test contact access functionality on the physical devices on which you plan to deploy your Lightning app. **ContactsService Considerations** Be aware of the following considerations when using ContactsService in your Lightning app. - ContactsService is built on top of mobile operating system and device features. ContactsService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of ContactsService can change without notice. - A Lightning component that uses ContactsService can have a custom user interface in the component itself. However, the contacts selection user interface can’t be customized. - When exporting contacts, it is the developer's responsibility to create the contact object correctly. Ensure the data from Salesforce is mapped properly to the fields of the `Contact` object required by the API. - If an export fails, check the error code returned by the promise rejection. A `SAVE_OPERATION_FAILED` code indicates a problem saving the contact on the device, while permission-related error codes indicate the user has denied access. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the DocumentScanner API. **Device Limitations** - To scan documents using a mobile device’s camera, DocumentScanner requires permission to use the camera. Your user must grant your app access to the camera. The exact user experience is governed by the platform. The request happens automatically on first use, and is managed by the device itself, but you should plan for it when designing the user experience of your app. - To scan documents stored in the device photo library, DocumentScanner requires permission to access the photo library. Your user must grant your app access to the photo library. Again, the user experience is managed by the platform (iOS or Android). - In Android 11 or later, if the user taps “Deny” for permission to access the Camera app or photo library more than once during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. In previous versions of Android, users would see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have chosen to deny. If the user has denied permission to access the Camera app or photo library and needs to change their permissions to allow access, they can do so in their device’s settings. - DocumentScanner doesn’t implement scanning itself. Instead, it delegates document scanning and recognition to an underlying SDK implemented in native code (Android or iOS). While the features provided by DocumentScanner are the same across both platforms, they’re subject to some platform-specific quirks and minor differences. - If the chosen input for the document to be scanned is the device camera, DocumentScanner automatically uses the “main” device camera. Built-in controls allow choosing other device cameras, if available. - If you can’t get a clear picture of the document, it can’t be recognized. The quality of the device camera affects text recognition. A damaged or low-quality camera lens or focusing system, poor lighting, motion, and other factors can make it difficult or impossible to get a clear picture of a document. - The quality of the document affects text recognition. Specifically, documents with damaged or obscured text are hard to recognize successfully. - DocumentScanner recognizes printed text and handwritten form factors. However, DocumentScanner provides the most accurate results when scanning printed text compared handwritten text, which varies on the legibility of handwritten characters. While DocumentScanner is capable of performing text recognition on a variety of typefaces, highly stylized fonts can lower recognition accuracy. **Development Considerations** - DocumentScanner requires access to camera hardware, or to the device photo library. To test scanning using a camera during development, use actual, physical devices. - The Android emulator can simulate camera hardware by using a webcam on your development system. To do so, edit the camera configuration for your Android Virtual Device, in the advanced settings panel. However, the camera built into most laptops is much lower quality than what’s found on modern mobile phones. A low-quality camera limits the usefulness of testing text recognition. - The iOS simulator doesn’t provide access to simulated camera hardware at all. You can certainly develop the user experience for your component on a desktop or laptop development system. But, be sure to test camera scanning functionality on the physical devices on which you plan to deploy your Lightning app. - As a work-around for limited camera access in virtual devices, you can load a few sample images into the virtual device’s photo library, and use those for scanning operations. However, if you expect your users to scan using a device camera, be sure to also test using real device cameras. **DocumentScanner Considerations** DocumentScanner is built on top of mobile operating system and device features. DocumentScanner’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of DocumentScanner can change without notice. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the GeofencingService API. **Device Limitations** - GeofencingService requires the use of the mobile device location detection hardware. The user must grant your app access to the device’s location. The exact user experience is governed by the platform. The request happens automatically on first use, and is managed by the device itself, but you should plan for it when designing the user experience of your app. - In Android 11 or later, if the user taps “Deny” for permission to access the mobile device location more than once during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. In previous versions of Android, users would see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have chosen to deny. If the user has denied permission to access the mobile device location and needs to change their permissions to allow access, they can do so in their device’s settings. - Location tracking is subject to significant privacy, processing, and power use restrictions, imposed by the underlying platform (Android or iOS). See important details in the GeofencingService API reference documentation. - Many factors affect the accuracy of location detection, the speed of determining the current location, and how much impact location tracking has on battery life. - Mobile devices vary in the quality of the location detection they provide. - If a mobile device can’t determine its location, neither can GeofencingService. The quality of the device’s positioning hardware, tall or dense buildings, indoor use, and other external factors can reduce the accuracy of location determination. - Location tracking on high accuracy can significantly increase power use, which affects how quickly a mobile device drains its battery. **Development Considerations** GeofencingService requires access to positioning hardware, such as GPS, Wi-Fi, cellular, and other location-detection hardware of your mobile device. To test location services during development, use actual, physical devices when possible. - The Android emulator and iOS simulator can each be configured to provide simulated location details. - Neither virtual device accurately simulates location detection in the real world, especially for environments where location detection is challenging. You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test geofencing-based functionality on the physical devices on which you plan to deploy your Lightning app. **GeofencingService Considerations** Be aware of the following considerations when using GeofencingService in your Lightning app. - GeofencingService is built on top of mobile operating system and device features. GeofencingService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of GeofencingService can change without notice. - There’s a maximum number of 20 monitored geofences at any time. # Considerations and Limitations Keep these guidelines and limitations in mind when developing features that use the HealthService API. **Supported Data** In this release, HealthService supports reading and writing body-weight records only. Each weight value is expressed in kilograms (kg) or pounds (lbs). The device’s health platform stores body mass without a unit. When you read records with `getWeight()`, HealthService converts the values to the unit that you specify in the `preferredUnit` option. If you don’t specify a unit, HealthService returns values in kilograms. **Device Limitations** HealthService doesn’t manage health data itself. Instead, it reads and writes data in the underlying platform’s health store, Apple HealthKit on iOS or Android Health Connect on Android. While the features provided by HealthService are the same across both platforms, they’re subject to some platform-specific quirks and minor differences. - HealthService requires the user to grant your app access to their health data. The exact user experience is governed by the platform. The request happens automatically the first time your component reads or writes data, and is managed by the device itself, but plan for it when you design the user experience of your app. - If the user denies permission, the promise is rejected with a `HealthServiceFailure.code` value of `USER_DENIED_PERMISSION`. If the user has denied permission and needs to change it to allow access, they can do so in their device’s settings. - On Android, the user must have the Health Connect provider installed. If it isn’t installed or needs an update, HealthService prompts the user to install or update it through the Google Play Store, and then the promise is rejected with a `PROVIDER_NOT_INSTALLED` or `PROVIDER_UPDATE_REQUIRED` code so that your component can display a message. - Read and write access are granted independently. Granting permission to read weight data doesn’t grant permission to write it, and the reverse is also true. If you’re having trouble getting HealthService to access health data, try these steps. 1. First, verify that you’ve granted health data permission to the mobile app where your component is running. You can check this in your device’s settings. 2. Next, on Android, verify that the Health Connect provider is installed and up to date. 3. Finally, double-check the configuration of the options that you pass to `getWeight()` and the structure of the record that you pass to `writeWeight()`. **Development Considerations** Virtual devices don’t always have health data when they’re created. To test reading weight history on a virtual device, first write some weight records with `writeWeight()`, or add records in the device’s native health app. You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test health data functionality on the physical devices on which you plan to deploy your Lightning app. Apple and Google provide their own guidance for working with health data. - iOS: [HealthKit (Apple)](https://developer.apple.com/documentation/healthkit) - Android: [Health Connect (Google)](https://developer.android.com/health-and-fitness/health-connect) **HealthService Considerations** Be aware of these considerations when using HealthService in your Lightning app. - HealthService is built on top of mobile operating system and device features. HealthService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of HealthService can change without notice. - A Lightning component that uses HealthService can have a custom user interface in the component itself. However, the permission dialog presented by the device can’t be customized. - Health data is sensitive. When you read health data from the device, handle it responsibly and in accordance with your company’s privacy policies and applicable regulations. - When writing a weight record, it’s the developer’s responsibility to construct the `WeightRecord` object correctly. Provide a value greater than 0 and a valid unit. - If an operation fails, check the error code returned by the promise rejection. A `SERVICE_NOT_ENABLED` code indicates that the capability is turned off for the app, while permission-related error codes indicate that the user has denied access. # Considerations and Limitations Keep the following in mind when developing features that use the LocationService API. **Device Limitations** LocationService doesn’t implement location calculation itself. Instead, it makes available certain location features of the underlying platform (Android or iOS) and hardware (phone or other mobile device). While the features provided by LocationService are the same across both platforms, they are subject to some platform-specific quirks and minor differences. - LocationService requires the use of the mobile device location detection hardware. The user must grant your app access to the device’s location. The exact user experience is governed by the platform. The request happens automatically on first use, and is managed by the device itself, but you should plan for it when designing the user experience of your app. - In Android 11 or later, if the user taps “Deny” for permission to access the mobile device location more than once during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. In previous versions of Android, users would see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have chosen to deny. If the user has denied permission to access the mobile device location and needs to change their permissions to allow access, they can do so in their device’s settings. - Location tracking is subject to significant privacy, processing, and power use restrictions, imposed by the underlying platform (Android or iOS). See important details in the [LocationService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-locationservice.html) reference documentation. - Many factors affect the accuracy of location detection, the speed of determining the current location, and how much impact location tracking has on battery life. - Mobile devices vary in the quality of the location detection they provide. - If a mobile device can’t determine its location, neither can LocationService. The quality of the device’s positioning hardware, tall or dense buildings, indoor use, and other external factors can reduce the accuracy of location determination. - Location tracking on high accuracy can **significantly** increase power use, which affects how quickly a mobile device drains its battery. If you’re having trouble getting LocationService to provide an accurate location, try the following: - First, verify that the device is able to determine its location. If the standard Maps app can’t get an accurate location, neither can LocationService. - Next, verify that the user has granted location access to the mobile app where your component is running. - Finally, double-check the configuration of LocationService in your code. In particular, verify that you’ve set the accuracy level as needed for your component’s features. **Development Considerations** LocationService requires access to positioning hardware, such as GPS, Wi-Fi, cellular, and other location-detection hardware of your mobile device. To test location services during development, use actual, physical devices when possible. - The Android emulator and iOS simulator can each be configured to provide simulated location details. - Neither virtual device accurately simulates location detection in the real world, especially for environments where location detection is challenging. You can certainly develop the user experience for your component on a desktop or laptop development system. But be sure to test location-based functionality on the physical devices on which you plan to deploy your Lightning app. **LocationService Considerations** Be aware of the following considerations when using LocationService in your Lightning app. - LocationService is built on top of mobile operating system and device features. LocationService’s location capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of LocationService can change without notice. - LocationService doesn’t provide map data. To display the current location on a map, you need to add extra functionality, for example, to retrieve map tile graphics. - LocationService detects a device’s current location only. While you can receive updates when the current location changes, updates provide only the new location. If needed, perform distance, proximity, or geofencing calculations yourself, in your own JavaScript. **important:** While it’s possible and not too difficult, a manually implemented geofencing feature can result in **severe** battery drain on devices that use it. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the NFCService API. **Device Limitations** - In Android 11 or later, if the user denies permission to access NFC functionality more than one time during the app’s lifetime of installation on a device, the user won’t see the system permissions dialog again. Tapping Deny multiple times implicitly chooses the “don’t ask again” option. - In previous versions of Android, users see the system permissions dialog each time the app requested permission unless the user had previously selected “don’t ask again”. This change in Android 11 discourages repeated requests for permissions that users have selected to deny. - If the user has denied permission to access NFC functionality and must change their permissions to allow access, they can do so in their device’s settings. **Development Considerations** - NFCService requires access to NFC hardware. To test NFC interactions during development, use actual, physical devices. **note:** NFCService allows for an action that, if used irresponsibly or incorrectly, can lead to irreversible consequences for your users. This dangerous action is the capability to erase NFC tags from a mobile device. As with all mobile capabilities, implementation of NFCService’s functionality, dangerous actions included, is at your discretion. Use caution when using dangerous actions in your component. **NFCService Considerations** - The NFCService plugin only interacts with NFC tags that are compliant with the NFC Data Exchange Format (NDEF) standard. - NFCService is built on top of mobile operating system and device features. NFCService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of NFCService can change without notice. # Considerations and Limitations Consider these guidelines and limitations when developing features that use the PaymentsService API. **PaymentsService Considerations** Be aware of the following considerations when using PaymentsService in your Lightning app. - PaymentsService is built on top of mobile operating system and device features. PaymentsService’s capabilities therefore depend on Android or iOS features, which are subject to change beyond our control. When mobile operating system features change, the behavior of PaymentsService can change without notice. - Calling `getSupportedPaymentMethods` or `collectPayment` requires passing in an options object. - The options object has some required fields and missing those fields results in the Payments plugin not working properly. See the PaymentsService API for the required fields. - Tap to Pay on Android devices must be on Android 13 or higher. - The Android device’s KeyStore must support [hardware-backed key agreements](https://developer.android.com/reference/android/content/pm/PackageManager#FEATURE_HARDWARE_KEYSTORE). - This requirement depends on the hardware capabilities of the device. An Android device on Android 12 or lower, even if the device is upgraded to Android 13, might not meet the requirement. Most modern Android devices should already support this capability, but older or lower-end devices may not. - For example, devices like the Samsung Galaxy Tab Active4 Pro are no longer supported in Stripe SDK versions 5.0.0 and higher (according to official Stripe documentations). - Developer Options must be disabled to start and complete a Tap to Pay transaction. If Developer Options are enabled, an error message is shown indicating they must be turned off. - If Developer Options are enabled, the user must quit the app, disable Developer Options, and then relaunch the app. # Considerations and Limitations Keep these considerations and limitations in mind when working with Lightning message service in Visualforce. ## Considerations Lightning message service doesn’t work for Visualforce’s `sforce.one` library when pages are loaded in the Chatter Publisher that uses ``. Use the native Lightning Publisher instead. Lightning message service doesn’t work in Visualforce pages that are included in Lightning Experience via iframes, including ``, ``, and the standard HTML ` ``` **See Also** - [apex:iframe](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-iframe.md) # Queries and the Partner WSDL When using the `query()` call with the partner WSDL, consider the following guidelines: - The queryString parameter is case-insensitive. The API will accept field names in the *fieldList* using any combination of uppercase and lowercase letters. However, in the [QueryResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query-queryresult.md), the case of field names (both predefined and custom fields) will match exactly the value in the `name` field of the Field type in the [DescribeSObjectResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-describesobjects-describesobjectresult.md). It is recommended that you use the proper case when specifying fields in the *fieldList*. - For the partner WSDL, the ordering of fields in the [QueryResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query-queryresult.md) is determined by the field order in the *fieldList*, not the field order in the WSDL file. - The *fieldList* cannot contain duplicate field names. For example: - Invalid (returns an error): `"SELECT Firstname, Lastname, Firstname FROM User"` - Valid: `"SELECT Firstname, Lastname FROM User"` - The [QueryResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query-queryresult.md) always contains all of the fields specified in the *fieldList*, even if some of the fields contain no data (`null`). Although SOAP allows you to omit fields that contain no values in the result set, the API always returns an array containing all fields. When using the `query()` call or `retrieve()` call with the partner WSDL, consider the following guideline: - A query that includes ID will return the ID field twice in the SOAP XML response data. Similarly, a query that does not include ID will return a single null ID field in the SOAP XML response data. For example, a query for `SELECT ID, FirstName, LastName FROM Contact` might return a SOAP XML response with records like: ```nolang Contact 0038000000FrjoBQRW 0038000000FrjoBQRW John Smith ``` This is expected behavior and something to be aware of if you are accessing the full SOAP XML response data and not using WSC to access the web service response. # Query Runs the specified SOQL query. When a SOQL query is executed, up to 2,000 records can be returned at a time in a synchronous request. However, to optimize performance, the returned batch can include fewer records than the limit or what's set in the request, based on the size and complexity of records queried. If the total number of results exceeds the limit or the requested number of results, the response contains the first batch of records, a `false` value for `done`, and a query locator. You can use the query locator with the [Query More Results](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-query-more-results.md) resource to retrieve the next batch of records. The response contains the total number of records returned by the Query request (`totalSize`), a boolean indicating whether there are no more results (`done`), the URI of the next set of records (`nextRecordsUrl`), and an array of query result records (`records`). ## Syntax **URI:** `/services/data/vXX.X/query?q=query` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`q`|A SOQL query. To create a valid URI, replace spaces in the query string with a plus sign `+` or with `%20`. For example: `SELECT+Name+FROM+MyObject`. If the SOQL query string is invalid, a MALFORMED_QUERY response is returned.| ## Example **Example Response Body** ```nolang { "totalSize": 3222, "done": false, "nextRecordsUrl": "/services/data/v68.0/query/01gRO0000016PIAYA2-500", "records": [ { "attributes": { "type": "Contact", "url": "/services/data/v68.0/sobjects/Contact/003RO0000035WQgYAM" }, "Id": "003RO0000035WQgYAM", "Name": "John Smith" }, ... ] } ``` ## Resources for Running SOQL Queries - For an example, see [Execute a SOQL Query.](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm) - To change the batch size, see [Query Options Header](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_queryoptions.htm). - To get feedback on a query and a report by using the `explain` parameter, see [Get Feedback on Query Performance](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query_explain.htm). - For more information on SOQL in general, see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm). # Query Event Monitoring Data with REST Use the Query resource to retrieve field values from a record. Specify the fields you want to retrieve in the fields parameter and use the `GET` method of the resource. You can use REST API to query event monitoring data. To retrieve event monitoring records based on `LogDate` and `EventType`, use a GET request like this: ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/query?q=SELECT+Id+,+EventType+,+LogFile+ ,+LogDate+,+LogFileLength+FROM+EventLogFile+WHERE+ LogDate+>+Yesterday+AND+EventType+=+'API' -H "Authorization: Bearer token" ``` ## Example raw response ```nolang { "totalSize" : 4, "done" : true, "records" : [ { "attributes" : { "type" : "EventLogFile", "url" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000001bROAQ" }, "Id" : "0ATD000000001bROAQ", "EventType" : "API", "LogFile" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000001bROAQ/LogFile", "LogDate" : "2014-03-14T00:00:00.000+0000", "LogFileLength" : 2692.0 }, { "attributes" : { "type" : "EventLogFile", "url" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000001SdOAI" }, "Id" : "0ATD000000001SdOAI", "EventType" : "API", "LogFile" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000001SdOAI/LogFile", "LogDate" : "2014-03-13T00:00:00.000+0000", "LogFileLength" : 1345.0 }, { "attributes" : { "type" : "EventLogFile", "url" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000003p1OAA" }, "Id" : "0ATD000000003p1OAA", "EventType" : "API", "LogFile" : "/services/data/v68.0/sobjects/EventLogFile/0ATD000000003p1OAA/LogFile", "LogDate" : "2014-06-21T00:00:00.000+0000", "LogFileLength" : 605.0 }, { "attributes" : { "type" : "EventLogFile", "url" : "/services/data/v68.0/sobjects/EventLogFile/0ATD0000000055eOAA" }, "Id" : "0ATD0000000055eOAA", "EventType" : "API", "LogFile" : "/services/data/v68.0/sobjects/EventLogFile/0ATD0000000055eOAA/LogFile", "LogDate" : "2014-07-03T00:00:00.000+0000", "LogFileLength" : 605.0 } ] } ``` # Query Hourly Event Log Files You query hourly event log files in the same way you query 24-hour log files. Suppose you’re an administrator. Your Chief Security Officer asks you to identify who modified specific accounts and opportunities in the past two hours. You query the hourly URI event log files using the EventLogFile object to review the page requests and request status. Because EventLogFile also returns 24-hour log files, use this SOQL syntax to filter out the 24-hour log files. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/query?​q=SELECT+Id+,​+EventType+,​+Interval+,+LogDate+,​+LogFile+​FROM+EventLogFile+​WHERE+EventType+=+'URI'+​AND+Interval+=+'Hourly' -H "Authorization: Bearer token" ``` In the query, `Interval=Hourly` makes sure that only hourly event log file data is returned. Alternatively, you can use `Sequence` to filter out 24-hour event log files (`Sequence!=0`). To get both hourly and 24-hour files, use `Sequence>=0`. If your sandbox org has URI events, you see log file records in your query results. You can also download the event log files to review the data in a CSV file. For more information, see [Trailhead: Download and Visualize Event Log Files](https://trailhead.salesforce.com/event_monitoring/event_monitoring_download). # Query More Results Returns the next batch of results from a SOQL query using a query locator. If the number of results returned from a SOQL query exceeds the number of requested records or the limit, the response contains a batch of results, a `false` value for `done`, and a query locator. Use the query locator in another request to retrieve the next batch of records. If there are still more records to be returned, the response contains a new query locator and `done` is `false`. You can continue retrieving results from the initial query until `done` is `true`, which indicates that all results are returned. The response contains the total number of records returned by the QueryAll request (`totalSize`), a boolean indicating whether there are no more results (`done`), the URI of the next set of records (`nextRecordsUrl`), and an array of query result records (`records`). ## Syntax **URI:** `/services/data/vXX.X/query/queryLocator` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`queryLocator`|A string used to retrieve the next set of query results. If there are more results to be retrieved, the previous set of query results contains the query locator in the `nextRecordsUrl` field.| ## Example **Example Response Body** ```nolang { "totalSize": 3222, "done": false, "nextRecordsUrl": "/services/data/v68.0/query/01gRO0000016PIAYA2-500", "records": [ { "attributes": { "type": "Contact", "url": "/services/data/v68.0/sobjects/Contact/003RO0000035WQgYAM" }, "Id": "003RO0000035WQgYAM", "Name": "John Smith" }, ... ] } ``` ## Resources for Executing SOQL Queries - For an example of how to use the query locator see [Execute a SOQL Query.](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm) - For another option to change the batch size, see [Query Options Header](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_queryoptions.htm). - For more information on SOQL in general, see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm). # Query Multi-Select Picklists You can search for individual values in multi-select picklists, which are regularly used in client applications. Client applications use a specific syntax for querying multi-select picklists, which allows selection of multiple items . In API version 39.0 and later, query for picklist values by the value’s API name, which can be different from the actual value. The following operators are supported for querying multi-select picklists: | Operator | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------ | | `=` | Equals the specified string. | | `!=` | Does not equal the specified string. | | `includes` | Contains the specified string. | | `excludes` | Does not contain the specified string. | | `;` | Specifies AND for two or more strings. Use `;` for multi-select picklists when two or more items must be selected. | Example `;` operator: ```nolang 'AAA;BBB' ``` ## Examples The following query filters on values in the `MSP1__c` field that are equal to `AAA` and `BBB` selected (exact match): ```soql SELECT Id, MSP1__c FROM CustObj__c WHERE MSP1__c = 'AAA;BBB' ``` In the following query: ```soql SELECT Id, MSP1__c from CustObj__c WHERE MSP1__c includes ('AAA;BBB','CCC') ``` the query filters on values in the `MSP1__c` field that contains either of these values: - `AAA` and `BBB` selected. - `CCC` selected. A match will result on any field value that contains 'AAA' and 'BBB' or any field that contains 'CCC'. For example, the following will be matched: - matches with ' `AAA;BBB`': ```nolang 'AAA;BBB' 'AAA;BBB;DDD' ``` - matches with ' `CCC`': ```nolang 'CCC' 'CCC;EEE' 'AAA;CCC' ``` # Query Options Header Specifies options used in a query, such as the query results batch size. Use this request header with the Query resource. ## Header Field Name and Values - **Field name**: `Sforce-Query-Options` - **Field values**: - `batchSize`—A numeric value that specifies the number of records returned for a query request. Child objects count toward the number of records for the batch size. For example, in relationship queries, multiple child objects are returned per parent row returned. The default is 2,000; the minimum is 200, and the maximum is 2,000. There is no guarantee that the requested batch size is the actual batch size. Changes are made as necessary to maximize performance. - **Example**: `Sforce-Query-Options: batchSize=1000` # Query or View Hourly Event Log Files To review events in your org on an accelerated basis, get event log files in hourly increments for recent activity. Hourly event log files can give you quicker visibility into security anomalies and custom code performance issues. |Required Editions| |-----------------| |Available in: **Enterprise**, **Performance**, **Unlimited**, and **Developer** Editions| |User Permissions Needed| | |-----------------------|--| |To access the API and query log files:|API Enabled AND View Event Log Files| |To view event log files:|View All Data| **Examples** Suppose you’re a security analyst monitoring for anomalous user behavior. By pulling more frequent updates into your security system, you can be alerted that a suspicious event has taken place within hours, rather than one or two days later. In another example, let’s say you’re a developer. You’ve identified a series of Apex failures in your org, and you want to proactively refactor your Apex code to improve performance. You review hourly log files to pinpoint the issues and fix your code in hours, before your end users start complaining about poor performance. **Considerations** - Hourly event log file integration with the Event Monitoring Analytics app is unavailable. - Depending on event delivery and final processing time, an event is expected to take three to six hours from the time of the event to be available in the log file. However, it can take longer. - When delays in processing occur and event logs for a particular hour arrive later, a new log file is created for the event/date/hour and lists only the new events. Use the creation date and an incremental sequence number to identify a new log file. Always use the most recently processed event log file for a particular date. However, if event log files have already been pulled into a third-party application, they could require deduplication in that application. If both hourly and daily logs are enabled, daily logs always have a sequence number of 0 because there is only one file per daily interval. CreatedDate indicates when the file was generated. If CreatedDate is after the last event log file download, there are new events to be processed. For best practices, use CreatedDate in the WHERE clause to select logs created after the last downloaded event log file. For example, if the last downloaded file was at 12PM 2/1/2018, to find the next log file, use +CreatedDate+\>+"2018-02-01T12:00:00Z" in the WHERE clause. - Your event log files may show a gap in data during site switches, instance refreshes, or unplanned system outages. However, during site switches and instance refreshes, Salesforce makes a commercially reasonable effort to avoid such data loss by using an automated process to replicate event logs. - In the unlikely case in which no log files are generated for 24 hours, contact Salesforce Support. - **[Query Hourly Event Log Files](https://developer.salesforce.com/docs/platform/api-rest/guide/event-log-file-hourly-query.md)** You query hourly event log files in the same way you query 24-hour log files. - **[Differences Between Hourly and 24-Hour Event Logs](https://developer.salesforce.com/docs/platform/api-rest/guide/event-log-file-hourly-diff.md)** You receive event log files approximately every hour in addition to 24-hour log files. Review the differences between the two logs so that you can filter your files to analyze the event data you want. # Query Performance Feedback (Beta) Analyzes the performance of a specified SOQL query, report, or list view without executing it. Use the `explain` parameter in a request to get a response that details how Salesforce processes your query, report, or list view and how to optimize it. The Query Performance Feedback resource is available in API version 30.0 and later. **note:** This feature is a Beta Service. Customer may opt to try such Beta Service in its sole discretion. Any use of the Beta Service is subject to the applicable Beta Services Terms provided at [Agreements and Terms](https://www.salesforce.com/company/legal/agreements/). ## Syntax **URI:** `/services/data/vXX.X/query?explain=query` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`explain`|A SOQL query, report, or list view that you want to analyze. To analyze a query, provide the full query in the request. To analyze a report or list view, provide the ID of the report or list view. If the SOQL query string is invalid, a MALFORMED_QUERY response is returned. If the report or list view ID is invalid, an INVALID_ID response is returned.| **Response body** The response body contains one or more plans that can be used to execute the query, report, or list view. The plans are sorted from most optimal to least optimal. Each plan has the following information: |Name|Type|Description| |----|----|-----------| |`cardinality`|number|The estimated number of records the query would return, based on index fields, if any.| |`fields`|string[]|If the leading operation type is `Index`, these values are the index fields used for the query. Otherwise, the value is null.| |`leadingOperationType`|string|The primary operation type that can use to optimize the query. This type can be one of these values: Index—The query uses an index on the query object; Other—The query uses optimizations internal to Salesforce; Sharing—The query uses an index based on the user’s sharing rules. If there are sharing rules that limit which records are visible to the current user, those rules can optimize the query; or TableScan—The query scans all records for the query object, and doesn’t use an index.| |`notes`|feedback note[]|An array of one or more feedback notes. Each note contains `description` (a detailed description of a part of the optimization; this description can include information on optimizations that can’t be used and why they can’t used), `fields` (an array of one or more fields used for the optimization), and `tableEnumOrId` (the table name for the fields used for the optimization). This response field is available in API version 33.0 and later.| |`relativeCost`|number|The cost of this query compared to the SOQL selective query threshold. A value greater than 1.0 means the query isn’t selective. For more information on selective queries, see [Working with Very Large SOQL Queries](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm) in the *Apex Developer Guide*.| |`sobjectCardinality`|number|The approximate count of all records in your organization for the query object.| |`sobjectType`|string|The name of the query object, such as `Merchandise__c`.| ## Resources for Executing SOQL Queries - For an example of how to use the `explain` parameter, see [Get Feedback on Query Performance](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query_explain.htm). - For more information on SOQL in general, see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm). # query() Executes a query against the specified object and returns data that matches the stated conditions. ## Syntax ```java QueryResult = connection.query(string queryString); ``` ## Usage Use the `query()` call to retrieve data from an object. When a client application invokes the `query()` call, it passes in a query expression that specifies the object to query, the fields to retrieve, and any conditions that determine whether a given object qualifies. For details about the syntax and rules used for queries, see the [Salesforce SOQL and SOSL Reference Guide: SOQL SELECT Syntax](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select.htm). Upon invocation, the API executes the query against the specified object, caches the results of the query on the API, and returns the query response object `QueryResult` . The client application can then use methods on `QueryResult` to iterate through rows in the query response and retrieve information. Your client application must be logged in with sufficient access rights to query the specified objects and to query the fields in the specified field list. For more information, see [Factors that Affect Data Access](https://developer.salesforce.com/docs/platform/api/guide/calls.md). An object must be configured to query using the API, and some objects can't be queried via the API. To determine if an object can be queried, use the [`describeSObjects()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-describesobjects.md) call on the object and inspect its `queryable` property. **tip:** If you use the enterprise WSDL, don't use `describe` to populate a select list. For example, if a Salesforce admin adds a field to the sObject after you consume it, the `describe` call pulls down the field but your toolkit won't know how to serialize it, and your integration fails. The `query()` call automatically filters out deleted and archived records. Use queryAll() to include deleted or archived records in the results. The query result object can return up to 2,000 rows of data. The max is also the default. However, to optimize performance, the returned batch size can be lower than the max or what's set in the request, based on the size and complexity of records queried. If the query results exceed the default, use the [`queryMore()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md) call to retrieve additional rows in batches. Adjust the default results batch in the [QueryOptions](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-queryoptions.md) header. For more information and examples on updating batch size, see [Change the Batch Size in Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_changing_batch_size.htm) in the *SOQL and SOSL Reference*. Queries that take longer than two minutes to process time out. For timed out queries, the API returns an API fault element of [`InvalidQueryLocatorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md). If a timeout occurs, refactor your query to return or scan a smaller amount of data. When querying for fields of type [base64](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/primitive_data_types.htm#i1435003) the query response object returns only one record at a time. You can't alter this process by changing the batch size of the `query()` call. **note:** For multicurrency organizations, special handling is required when querying currency fields containing values in different currencies. For example, if a client application is querying [PricebookEntry](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_pricebookentry.htm) objects based on values in the `UnitPrice` field, and if the `UnitPrice` amounts are expressed in different currencies, then the query logic must handle this case correctly. For example, if the query is trying to retrieve the product codes of all products with a unit price greater than or equal to $10 USD, the query expression looks something like this: ```codesegment SELECT Product2Id,ProductCode,UnitPrice FROM PricebookEntry WHERE (UnitPrice >= 10 and CurrencyIsoCode='USD') OR (UnitPrice >= 5.47 and CurrencyIsoCode='GBP') OR (UnitPrice >= 8.19 and CurrencyIsoCode='EUR') ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`queryString`|string|Contains the SOQL query, which specifies the object to query, the fields to return, and any conditions for including a specific object in the query. See [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.htm).| ## Sample Code—Java This sample executes a query that fetches the first names and last names of all contacts. It calls `query()` with the query string to get the first batch of records. This example also calls `queryMore()` in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console. ```codesegment public void queryRecords() { QueryResult qResult = null; try { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; qResult = connection.query(soqlQuery); boolean done = false; if (qResult.getSize() > 0) { System.out.println("Logged-in user can see a total of " + qResult.getSize() + " contact records."); while (!done) { SObject[] records = qResult.getRecords(); for (int i = 0; i < records.length; ++i) { Contact con = (Contact) records[i]; String fName = con.getFirstName(); String lName = con.getLastName(); if (fName == null) { System.out.println("Contact " + (i + 1) + ": " + lName); } else { System.out.println("Contact " + (i + 1) + ": " + fName + " " + lName); } } if (qResult.isDone()) { done = true; } else { qResult = connection.queryMore(qResult.getQueryLocator()); } } } else { System.out.println("No records found."); } System.out.println("\nQuery succesfully executed."); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample executes a query that fetches the first names and last names of all contacts. It calls `query()` with the query string to get the first batch of records. This example also calls [queryMore()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md) in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console. ```class public void queryRecords() { QueryResult qResult = null; try { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; qResult = binding.query(soqlQuery); Boolean done = false; if (qResult.size > 0) { Console.WriteLine("Logged-in user can see a total of " + qResult.size + " contact records."); while (!done) { sObject[] records = qResult.records; for (int i = 0; i < records.Length; ++i) { Contact con = (Contact)records[i]; String fName = con.FirstName; String lName = con.LastName; if (fName == null) { Console.WriteLine("Contact " + (i + 1) + ": " + lName); } else { Console.WriteLine("Contact " + (i + 1) + ": " + fName + " " + lName); } } if (qResult.done) { done = true; } else { qResult = binding.queryMore(qResult.queryLocator); } } } else { Console.WriteLine("No records found."); } Console.WriteLine("\nQuery succesfully executed."); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Response [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) ## Faults [`MalformedQueryFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidSObjectFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidFieldFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [queryAll()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-queryall.md) - [queryMore()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md) - [API Call Basics](https://developer.salesforce.com/docs/platform/api/guide/calls.md) - [Change the Batch Size in Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_changing_batch_size.htm) # QueryAll Executes the specified SOQL query. Unlike the Query resource, QueryAll returns records that are soft deleted due to a merge or delete. After these records are permanently removed from the recycle bin, you can no longer query them. QueryAll also returns information about archived task and event records. This resource is available in REST API version 29.0 and later. When a QueryAll request is executed, up to 2,000 records can be returned at a time in a synchronous request. However, to optimize performance, the returned batch can include fewer records than the limit or what's set in the request, based on the size and complexity of records queried. If the total number of results exceeds the limit or the requested number of results, the response contains a batch of results, a `false` value for `done`, and a query locator. The query locator can be used with the [QueryAll More Results](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-queryall-more-results.md) resource to retrieve the next batch of records. Although the `nextRecordsUrl` has `query` in the URL, it still provides the remaining results from the initial QueryAll request. The remaining results include deleted records that matched the initial query. The response contains the total number of records returned by the QueryAll request (`totalSize`), a boolean indicating whether there are no more results (`done`), the URI of the next set of records (`nextRecordsUrl`), and an array of query result records (`records`). ## Syntax **URI:** `/services/data/vXX.X/queryAll?q=query` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`q`|A SOQL query. To create a valid URI, replace spaces with a plus sign `+` in the query string. For example: `SELECT+Name+FROM+MyObject`.| ## Example **Example Response Body** ```nolang { "totalSize": 3222, "done": false, "nextRecordsUrl": "/services/data/v68.0/query/01gRO0000016PIAYA2-500", "records": [ { "attributes": { "type": "Contact", "url": "/services/data/v68.0/sobjects/Contact/003RO0000035WQgYAM" }, "Id": "003RO0000035WQgYAM", "Name": "John Smith" }, ... ] } ``` ## Resources for Executing SOQL Queries - To run a query that includes deleted items, see [Execute a SOQL Query that Includes Deleted Items](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_queryall.htm). - To increase the batch size of query results, use the query identifier described in [Execute a SOQL Query](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm) or use the [Query Options Header](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_queryoptions.htm). - For more information about SOQL generally, see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm). # QueryAll More Results Returns the next batch of results from a QueryAll request using a query locator. This API resource executes the specified QueryAll request. This resource is available in REST API version 29.0 and later. If the number of results returned from a SOQL query exceeds the number of requested records or the limit, the response contains a batch of results, a `false` value for `done`, and a query locator. Use the query locator in a QueryAll More Results request to retrieve the next batch of records. If there are still more records to be returned, the response contains a new query locator and `done` is `false`. You can continue retrieving results from the initial QueryAll request until `done` is `true`, which indicates that all results are returned. **note:** The URI specified in the `nextRecordsUrl` field of a QueryAll response body contains `query` instead of `queryAll`. To retrieve the next set of results, you can use either the Query More Results or the QueryAll More Results resources with the same query locator. The remaining results include deleted records that match the initial query. For example, if the response body of a QueryAll request contains `"nextRecordsUrl": "/services/data/v68.0/query/01g5e00001AH2dOAAT-4000"`, you can retrieve the next set of QueryAll results with either URI. - `/services/data/v68.0/query/01g5e00001AH2dOAAT-4000` - `/services/data/v68.0/queryAll/01g5e00001AH2dOAAT-4000` The response contains the total number of records returned by the QueryAll request (`totalSize`), a boolean indicating whether there are no more results (`done`), the URI of the next set of records (`nextRecordsUrl`), and an array of query result records (`records`). ## Syntax **URI:** `/services/data/vXX.X/queryAll/queryLocator` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`queryLocator`|A string used to retrieve the next set of query results. If there are more results to be retrieved, the previous set of QueryAll results contains the query locator in the `nextRecordsUrl` field.| ## Example **Example Response Body** ```nolang { "totalSize": 3222, "done": false, "nextRecordsUrl": "/services/data/v68.0/query/01gRO0000016PIAYA2-500", "records": [ { "attributes": { "type": "Contact", "url": "/services/data/v68.0/sobjects/Contact/003RO0000035WQgYAM" }, "Id": "003RO0000035WQgYAM", "Name": "John Smith" }, ... ] } ``` ## Resources for Executing SOQL Queries - To send a QueryAll request that includes deleted items, see [Execute a SOQL Query that Includes Deleted Items](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_queryall.htm). - To increase the batch size of query results use the [Query Options Header](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_queryoptions.htm). - For more information about SOQL generally, see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm). # `queryAll()` Retrieves data from specified objects, including records that have been deleted or archived. **note:** Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain terms to avoid any effect on customer implementations. ## Syntax ```java QueryResult = connection.queryAll(string queryString); ``` ## Usage Use `queryAll()` to identify the records that have been deleted because of a merge or delete. `queryAll()` has read-only access to the field `isDeleted` but is otherwise the same as [`query()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query.md). Use `queryAll()` in preparation to undelete records with the [`undelete()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-undelete.md) call. To find records that have been deleted, specify `isDeleted = true` in the query string. For merged records, request the [`masterRecord`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-merge.md). For example: ```codesegment SELECT id, isDeleted, masterRecordId FROM Account WHERE masterRecordId='100000000000Abc' ``` Filter on the `isArchived` field to find only the archived objects. You can update or delete archived records, but you can't update the `isArchived` field. **note:** Because Salesforce doesn’t track changes to external data, `queryAll()` behaves the same as `query()` for external objects. ## Arguments |Name|Type|Description| |----|----|-----------| |`queryString`|string|Contains the SOQL query, which specifies the object to query, the fields to return, and any conditions for including a specific object in the query. See [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/).| ## Sample Code—Java This sample performs a query to get all the accounts, whether they’re deleted or not. It sets a custom batch size of 250 records. It fetches all batches of records by calling `queryAll()` the first time and then `queryMore()`. The names and the value of the isDeleted fields of all returned accounts are written to the console. ```codesegment public void queryAllRecords() { // Setting custom batch size connection.setQueryOptions(250); try { String soqlQuery = "SELECT Name, IsDeleted FROM Account"; QueryResult qr = connection.queryAll(soqlQuery); boolean done = false; if (qr.getSize() > 0) { System.out.println("Logged-in user can see a total of " + qr.getSize() + " contact records (including deleted records)."); while (!done) { SObject[] records = qr.getRecords(); for (int i = 0; i < records.length; i++) { Account account = (Account) records[i]; boolean isDel = account.getIsDeleted(); System.out.println("Account " + (i + 1) + ": " + account.getName() + " isDeleted = " + account.getIsDeleted()); } if (qr.isDone()) { done = true; } else { qr = connection.queryMore(qr.getQueryLocator()); } } } else { System.out.println("No records found."); } } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample performs a query to get all the accounts, whether they’re deleted or not. It sets a custom batch size of 250 records. It fetches all batches of records by calling `queryAll()` the first time and then `queryMore()`. The names and the value of the isDeleted fields of all returned accounts are written to the console. ```codesegment public void queryAllRecords() { // Setting custom batch size QueryOptions qo = new QueryOptions(); qo.batchSize = 250; qo.batchSizeSpecified = true; binding.QueryOptionsValue = qo; try { String soqlQuery = "SELECT Name, IsDeleted FROM Account"; QueryResult qr = binding.queryAll(soqlQuery); Boolean done = false; if (qr.size > 0) { Console.WriteLine("Logged-in user can see a total of " + qr.size + " contact records (including deleted records)."); while (!done) { sObject[] records = qr.records; for (int i = 0; i < records.Length; i++) { Account account = (Account)records[i]; Boolean isDel = (Boolean)account.IsDeleted; Console.WriteLine("Account " + (i + 1) + ": " + account.Name + " isDeleted = " + account.IsDeleted); } if (qr.done) { done = true; } else { qr = binding.queryMore(qr.queryLocator); } } } else { Console.WriteLine("No records found."); } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Response [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) ## Faults [`MalformedQueryFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidSObjectFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidFieldFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [API Call Basics](https://developer.salesforce.com/docs/platform/api/guide/calls.md) - [queryMore()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md) # QueryLocator A string returned in QueryResult and used in `queryMore()` to find and retrieve additional query results. Represents a server-side cursor. When results for a large or complex query can’t be returned in a single batch, one or more server-side cursors and corresponding query locators are automatically created. A cursor marks the location of additional query results in the database, and a query locator finds the cursor. A new `queryLocator` is returned in the [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) object when there are more records than can be returned by a `query()` or `queryMore()` call. To get the next set of results, follow up with a subsequent `queryMore()` call using the most recently returned query locator value. Use each `queryLocator` value only one time. You can't use `queryLocator` with queries that access a custom metadata type. For invalid query locators, the API returns the fault element `InvalidQueryLocatorFault` and a possible [extended error code](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#extendederrorcode) with additional information. **See Also** - [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) - [Core Data Types Used in API Calls](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) - [SOQL and SOSL Limits for Search Queries](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm) # `queryMore()` Retrieves the next batch of query results. ## Syntax ```nolang QueryResult queryResult = connection.queryMore(queryLocator) ``` `queryMore()` requires the `queryLocator` parameter, the value of which is the query locator id returned in the preceding `query()`. ## Usage Use this call to get additional results from a `query()` or a preceding `queryMore()` call that returns a large number of records. The `query()` and `queryMore()` calls can retrieve up to 2,000 records in a batch. If there are more results that can be returned in a single batch, a server-side cursor and a [QueryLocator](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-querylocator.md) are created. The query locator is returned in QueryResult, and used in `queryMore()` to find the next batch of results. The `queryMore()` call processes subsequent records in additional batches, resets the server-side cursor, and returns a newly generated query locator. To iterate through the records in the result set, call `queryMore()` repeatedly until all records in the result set have been processed and the `Done` flag is `true`. You can't use `queryMore()` if a query includes a `GROUP BY` clause. See [Salesforce SOQL and SOSL Reference Guide: `GROUP BY`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_groupby.htm) for more information. When querying external objects, Salesforce Connect accesses the external data in real time via Web service callouts, and each `queryMore()` call results in a callout. The batch boundaries and page sizes depend on your adapter and how you set up the external data source. We recommend: - Avoid paging by filtering your queries of external objects to return fewer rows than the batch size, which by default is 2,000 rows. Remember, obtaining each batch requires a `queryMore()` call, which results in a Web service callout. - If the external data frequently changes, avoid using `queryMore()` calls. If the external data is modified between `queryMore()` calls, you can get an unexpected `QueryResult`. If the primary object for a `SELECT` statement is an external object, `queryMore()` supports only that primary object and doesn’t support subqueries. See [Client-driven and Server-driven Paging for Salesforce Connect—OData 2.0 and 4.0 Adapters](https://help.salesforce.com/s/articleView?id=platform.odata_paging.htm&type=5). ## Sample Code—Java This sample executes a query that fetches the first names and last names of all contacts. It calls `query()` with the query string to get the first batch of records. It then calls `queryMore()` in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console. ```codesegment public void queryRecords() { QueryResult qResult = null; try { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; qResult = connection.query(soqlQuery); boolean done = false; if (qResult.getSize() > 0) { System.out.println("Logged-in user can see a total of " + qResult.getSize() + " contact records."); while (!done) { SObject[] records = qResult.getRecords(); for (int i = 0; i < records.length; ++i) { Contact con = (Contact) records[i]; String fName = con.getFirstName(); String lName = con.getLastName(); if (fName == null) { System.out.println("Contact " + (i + 1) + ": " + lName); } else { System.out.println("Contact " + (i + 1) + ": " + fName + " " + lName); } } if (qResult.isDone()) { done = true; } else { qResult = connection.queryMore(qResult.getQueryLocator()); } } } else { System.out.println("No records found."); } System.out.println("\nQuery succesfully executed."); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample executes a query that fetches the first names and last names of all contacts. It calls `query()` with the query string to get the first batch of records. It then calls `queryMore()` in a loop to get subsequent batches of records until no records are returned. It writes the first and last names of the contacts queried to the console. ```class public void queryRecords() { QueryResult qResult = null; try { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; qResult = binding.query(soqlQuery); Boolean done = false; if (qResult.size > 0) { Console.WriteLine("Logged-in user can see a total of " + qResult.size + " contact records."); while (!done) { sObject[] records = qResult.records; for (int i = 0; i < records.Length; ++i) { Contact con = (Contact)records[i]; String fName = con.FirstName; String lName = con.LastName; if (fName == null) { Console.WriteLine("Contact " + (i + 1) + ": " + lName); } else { Console.WriteLine("Contact " + (i + 1) + ": " + fName + " " + lName); } } if (qResult.done) { done = true; } else { qResult = binding.queryMore(qResult.queryLocator); } } } else { Console.WriteLine("No records found."); } Console.WriteLine("\nQuery succesfully executed."); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`queryLocator`|[QueryLocator](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-querylocator.md)|Points to a server-side cursor in the database. Tracks the current processing location in the query results set and indicates the location of additional results. A query locator is a specialized string, similar to an ID, and is 18 characters long and begins with the prefix `0r8`. Required for retrieving subsequent sets of objects from query results, if needed.| ## Response [QueryResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-queryresult.md) ## Faults [`InvalidQueryLocatorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [query()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query.md) - [API Call Basics](https://developer.salesforce.com/docs/platform/api/guide/calls.md) - [Change the Batch Size in Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_changing_batch_size.htm) # QueryOptions Specifies the preferred batch size for queries. The system sometimes creates batches that are larger or smaller than the specified size to maximize performance. ## Associated API Calls [`query()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query.md), [`queryMore()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-querymore.md), [`retrieve()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-retrieve.md) ## Fields ### `batchSize` **Type:** int **Description:** The batch size for the number of records returned in a `query()` or `queryMore()` call. Child objects count toward the number of records for the batch size. For example, in relationship queries, multiple child objects are returned per parent row returned. The default and the maximum are 2,000; the minimum is 200. There is no guarantee that the requested batch size is the actual batch size. To maximize performance, the number of results returned can vary based on the size and complexity of the records.. ## Sample Code For code examples, see Change the Batch Size in Queries in the [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/). # QueryResult A read-only SObject that contains query results and additional data about the query, returned in response to a `query()` or `queryMore()` call. QueryResult only returns responses to queries that don't use an [aggregate function](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm), such as `MAX()`. For queries with an aggregate function, results are returned in [AggregateResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-aggregateresult.md). The QueryResult object has these properties. |Name|Type|Description| |----|----|-----------| |`queryLocator`|[QueryLocator](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query-querylocator.md)|Points to a server-side cursor in the database. Tracks the current processing location in the query results set and indicates the location of additional results, A query locator is a specialized string, similar to an ID, and is 18 characters long and begins with the prefix `0r8`. Used in [`queryMore()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md) for retrieving subsequent sets of objects from the query results, if needed.| |`done`|boolean|Indicates whether additional rows must be retrieved from the query results (`false`) using [`queryMore()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-querymore.md), or not (`true`). Use this value as a loop condition while iterating through the query results.| |`records`|sObject[]|Array of [sObjects](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject) representing individual objects of the specified object and containing data defined in the field list specified in the [queryString](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-query.md).| |`size`|int|Total number of rows retrieved in the query. Use this value to determine whether the query retrieved any rows (size > 0) or not (size = 0). Querying external objects is supported, but an external data source doesn’t provide a count of the number of rows retrieved. When the number of rows retrieved from an external data source is unknown, the value is automatically set to size = -1.| # QueryResultIterator Iterate over query results returned by the AJAX Toolkit without invoking `queryMore` and `queryLocator`. ```javascript var result = sforce.connection.query("select id, name from account"); var it = new sforce.QueryResultIterator(result); while (it.hasNext()) { var account = it.next(); sforce.debug.log(account.Name); } ``` 1. The `sforce.connection.query` method returns a QueryResult object. 2. A QueryResultIterator object is created and passed the QueryResult object. 3. The code iterates through the records. # Quick Action API Considerations Before working with the Lightning Quick Action JavaScript API methods, review some considerations that might impact your implementation. **tip:** The Lightning Quick Action JavaScript APIs can only interact with quick actions that are targetable on the page. Review the following support. - Targetable: An action that displays in the highlights panel, including the dropdown action overflow - Targetable: An action that displays in the publisher, including the More overflow - Targetable: An action that’s nested in an accordion component section or tab that’s expanded by default - Not targetable: An action that’s nested in an accordion component section or tab that’s not expanded by default* *The action becomes targetable after a user opens the accordion section or tab containing the action. If you use the Lightning Quick Action JavaScript APIs in custom code in a Lightning app, the targeted quick actions must be visible on the page. If you target an action that isn’t visible on the page, it fails. The Quick Action APIs work with most action types. |Action Type|Supported?|Notes| |-----------|:--------:|-----| |Create a Record|Yes|Supported in all Lightning apps, on any object.| |Custom Visualforce|Yes|Supported in all Lightning apps, on any object. To work with these action types, use the `getCustomAction` method. Other methods aren’t supported for this action type.| |Flow|No|Results in error.| |Log a Call|Yes|Supported in all Lightning apps, on any object.| |Aura Component|Yes|Supported in all Lightning apps, on any object. To work with these action types, use the `getCustomAction` method. Other methods aren’t supported for this action type.| |Send Email|Yes|Supported in all Lightning apps, on any object.| |Update a Record|Yes|Supported in all Lightning apps, on any object.| The `lightning:quickActionAPI` component supports utility popout. However, the `getCustomAction` method doesn’t work with utility popout yet. The Salesforce Classic Publisher APIs also support utility popout if you place them in a Visualforce page that’s used in the utility bar. The `customActionMessage` doesn’t support utility popout either. The Quick Action APIs don’t support the following items. - Opportunity products - Knowledge articles - Crew Size field on the Service Crew object - Social quick action in the case feed publisher provided with Social Customer Service - Experience Cloud sites—the `lightning:quickActionAPI` component doesn’t work in Experience Cloud sites # Quick Action APIs in Lightning Experience A `lightning:quickActionAPI` component allows you to access methods for programmatically controlling quick actions on record pages. This component is supported in Lightning Experience and supports utility pop-out. This component requires API version 43.0 and later. | Required Editions | | --------------------------------------------------------------------------------------------------------------------- | | Available in: Lightning Experience | | Available in: **Group**, **Professional**, **Enterprise**, **Performance**, **Unlimited**, and **Developer** Editions | For example, if you have a custom Aura component that displays Knowledge articles, you can use the `lightning:quickActionAPI` component to attach and send a Knowledge article from your custom component using the Email quick action on the case record page. To access these methods, create an instance of the `lightning:quickActionAPI` component inside your Aura component or page and assign an `aura:id` attribute to it. ```xml ``` This component provides similar functionality to the [Publisher APIs in Salesforce Classic](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/case-feed-dev-guide-component-interactions.md). ## Sample Code This example creates two buttons that interact with the Update Case quick action on a case record page in Lightning Experience. The controller code uses the following Quick Action API methods: [selectAction](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-selectaction.md), [setActionFieldValues](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-setactionfieldvalues.md), and [invokeAction](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-invokeaction.md). Component code: ```html
``` Controller code: ```javascript ({ selectUpdateCaseAction: function (cmp, event, helper) { var actionAPI = cmp.find("quickActionAPI"); var args = { actionName: "Case.UpdateCase" }; actionAPI .selectAction(args) .then(function (result) { // Action selected; show data and set field values }) .catch(function (e) { if (e.errors) { // If the specified action isn't found on the page, // show an error message in the my component } }); }, updateCaseStatusAction: function (cmp, event, helper) { var actionAPI = cmp.find("quickActionAPI"); var fields = { Status: { value: "Closed" }, Subject: { value: "Sets by lightning:quickActionAPI component" }, accountName: { Id: "accountId" }, }; var args = { actionName: "Case.UpdateCase", entityName: "Case", targetFields: fields }; actionAPI .setActionFieldValues(args) .then(function () { actionAPI.invokeAction(args); }) .catch(function (e) { console.error(e.errors); }); }, }); ``` - **[Quick Action API Considerations](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-considerations.md)** Before working with the Lightning Quick Action JavaScript API methods, review some considerations that might impact your implementation. - **[getAvailableActions](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-getavailableactions.md)** Allows custom components to get a list of the available actions on a record page. - **[getAvailableActionFields](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-getavailableactionfields.md)** Allows custom components to get a list of the available fields for a specific action on a record page. - **[getCustomAction](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-getcustomaction.md)** Allows custom components to access a custom quick action and pass data or messages to it. - **[getSelectedActions](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-getselectedactions.md)** Allows custom components to access selected quick actions on a record page. - **[invokeAction](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-invokeaction.md)** Allows custom components to save or submit the quick action on a record page. - **[refresh](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-refresh.md)** Refreshes the current record page. - **[selectAction](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-selectaction.md)** Allows custom components to select and focus on a quick action on a record page. - **[setActionFieldValues](https://developer.salesforce.com/docs/platform/case-feed-dev-guide/guide/quickaction-api-setactionfieldvalues.md)** Allows custom components to select a quick action on a record page and then specify field values for that action. **See Also** - [Lightning Component Library: lightning:quickActionAPI](https://developer.salesforce.com/docs/component-library/bundle/lightning:quickActionAPI/documentation) - [_Lightning Components Developer Guide_](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/intro_framework.htm) # Quick Actions Use a quick action to create a task or a case. Invoke existing quick actions, both global and object-specific, to create records, update records, or log calls. For more information about creating global quick actions, see [Create Global Quick Actions](https://help.salesforce.com/HTViewHelpDoc?id=creating_global_actions.htm), and for more information on object-specific quick actions, see [Create Object-Specific Quick Actions](https://help.salesforce.com/HTViewHelpDoc?id=creating_object_specific_actions.htm), in Salesforce Help. This object is available in API version 32.0 and later. ## Supported REST HTTP Methods **URIs:** - Get a list of quick actions: `/services/data/vXX.X/actions/custom/quickAction` - Get a specific quick action: `/services/data/vXX.X/actions/custom/quickAction/quick_action_name` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` **Notes:** The only type of quick actions that can be invoked are create, update, and logACall. ## Inputs All quick actions have the `contextId` input parameter. It’s a reference to the related record for the quick action. Other inputs vary according to the layout of the quick action. To determine inputs for a specific quick action, use the describe feature. For example, perform a GET with `/services/data/vXX.X/actions/custom/quickAction/Task/deferTask` to see the inputs for the quick action `deferTask`. # Quick Actions Access global quick actions and object-specific quick actions. By using the POST method with this resource, you can create records using a quick action. This resource is available in REST API version 28.0 and later. When working with actions, also refer to [sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions.md). - **[Get Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions-get.md)** Gets a list of quick actions. This resource is available in REST API version 28.0 and later. - **[Create Records Using Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions-post.md)** Creates a record via a quick action. This resource is available in REST API version 28.0 and later. - **[Return Headers of Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions-head.md)** Returns only the headers that are returned by sending a GET request to the Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. # Quick Start To set up and run REST API, send a few basic requests to Salesforce. This Quick Start explains setting up a basic environment and updating a record using REST API. You can set up and use REST API in many ways, and the examples show how to use the free Developer Edition and cURL. 1. [Using cURL](https://developer.salesforce.com/docs/platform/api-rest/guide/quickstart-using-curl.md) Get to know the formatting that you can use with cURL to make requests to Salesforce. This Quick Start uses cURL examples, but you can use any tool or development environment that can make REST requests. 2. [Step One: Sign up for Salesforce Developer Edition](https://developer.salesforce.com/docs/platform/api-rest/guide/quickstart-dev-org.md) Developer Edition provides a free and easy solution so that you can use Salesforce for testing and development. 3. [Step Two: Set Up Authentication](https://developer.salesforce.com/docs/platform/api-rest/guide/quickstart-oauth.md) To successfully send requests, REST API requires an access token obtained by authentication. Although you can create and authenticate against your own connected app, these Quick Start examples use Salesforce CLI for convenience. Salesforce CLI is a connected app that you can authenticate, and it requires no work to configure. 4. [Step Three: Walk Through the Sample Code](https://developer.salesforce.com/docs/platform/api-rest/guide/quickstart-code.md) To access different types of resources in Salesforce, make a series of REST requests. Before you try these examples, make sure to complete the prerequisites and obtain an access token in Step 1 of this Quick Start. 5. [Using Other Tools](https://developer.salesforce.com/docs/platform/api-rest/guide/quickstart-using-other-tools.md) Other tools are available to obtain data from your Salesforce org. # Quick Start The quick start provides Trailhead resources for you to learn core Aura components concepts, and a short tutorial that builds an Aura component to manage selected contacts in the Salesforce mobile app and Lightning Experience. You’ll create all components from the Developer Console. The tutorial uses several events to create or edit contact records, and view related cases. # Quick Start This simple quick start shows you how to get started with Canvas by using the Heroku Quick Start. The Heroku Quick Start creates a “hello world” app on Heroku in either Java or Ruby, depending on the template you select. At the same time, it creates a corresponding canvas app in Salesforce. The Heroku app is a “hello world” Web page that calls the Canvas SDK to display information about the current user and lets you post to the current user’s Chatter feed. You can also specify where to display the Canvas app in Salesforce using the Canvas plugin for the external client app. - **[Prerequisites](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-prereqs.md)** Get the appropriate access and tools to complete the quick start steps. - **[Create the App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-create-app.md)** Create the Heroku “hello world” app and the associated canvas app in Salesforce. - **[Set the Canvas App Location for External Client Apps](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-set-app-location-eca.md)** Specify where your canvas app can display to a user in Salesforce via an external client app. - **[Set the Canvas App Location for Connected Apps](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-set-app-location.md)** Specify where your canvas app can display to a user in Salesforce via a connected app. **See Also** - [Prerequisites](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-prereqs.md) - [Create the App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-create-app.md) - [Set the Canvas App Location for Connected Apps](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-set-app-location.md) # Quick Start Tutorials These hands-on tutorials get you started with creating custom LWCs for your mobile apps. - **[Develop a Lightning Web Component Quick Action](https://developer.salesforce.com/docs/platform/mobile-offline/guide/quickstart-lwc-action.md)** Welcome to developing quick actions using Lightning web components (LWCs) in the Salesforce Field Service (SFS) mobile app. With custom quick actions, you can tailor your Field Service mobile app users’ experience to have easier access to viewing and updating information relevant to them. - **[Debug Lightning Web Components in the Field Service Mobile App](https://developer.salesforce.com/docs/platform/mobile-offline/guide/quickstart-lwc-debugging.md)** The best way to develop and debug your Lightning web components is the same way you develop and debug *anything* built with HTML, CSS, and JavaScript: with the debugging tools built into your web browser. # Quick Start—Advanced This advanced quick start shows you how to get started with more of the Canvas features. It takes you step-by-step through the process of creating, packaging, uploading, installing, and running a canvas app. The sample canvas app is a “hello world” Web page that calls the Canvas SDK to display the current user’s name. In this example, you: - Clone the “hello world” app from GitHub. - Run the app on a local Web server. - Expose the Web app as a canvas app in your Salesforce development org. You can either: - Use an external client app for your canvas app (recommended). - Use a connected app for your canvas app. **note:** In Spring ’26, the ability to create new connected apps is disabled by default. We recommend using [external client apps](https://help.salesforce.com/s/articleView?id=xcloud.external_client_apps.htm) for all new Canvas integrations. To enable creation of new connected apps, contact Salesforce Customer Support. - Test the app in the Canvas App Previewer. - Deploy the Web app to Heroku. - Package and upload the canvas app. - Install the canvas app in another Salesforce org and run it as a user would. The steps in this quick start assume you’re using Windows. You can use another OS, but there might be some minor differences in the steps. - **[Prerequisites](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-prereqs.md)** Get the appropriate access and tools to complete the quick start. - **[Clone the Project from GitHub](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-clone-the-project.md)** The “hello world” sample project is part of the Canvas SDK, which is located on GitHub. From GitHub, clone the project to make a copy of it on your local machine. - **[Run the Web App Locally](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-run-the-app-locally.md)** - **[Create the Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-intro-create.md)** To create a canvas app, you need the Customize Application and Modify All Data user permissions. - **[Configure Who Can Access the Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-intro-config-access.md)** To configure access for specific users, update the policies and profiles for the corresponding external client app or connected app. - **[Deploy the Web App to Heroku](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-upload-app-to-heroku.md)** After you run the web app locally and test it as a canvas app, deploy the web app to Heroku and run it from there. - **[Deploy the Canvas External Client App to an Org](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-deploy-canvas-app.md)** Deploy and retrieve your Canvas integration for the external client app with Metadata API. The Canvas plugin has its own settings files and policies file. - **[Update the Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-update-canvas-app-heroku.md)** In this step, you update the canvas app to run the “hello world” app that’s now running on Heroku. - **[Package the Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-intro-package.md)** Packaging is the first step in making your canvas app available for installation in another org. - **[Configure Who Can Access the Installed Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-config-who-can-access-installed-canvas-app.md)** **See Also** - [Introducing Canvas](https://developer.salesforce.com/docs/platform/canvas-framework/introducing/canvas-framework-intro.md) - [Prerequisites](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-prereqs.md) # Quick Start: Bulk API You process a set of records by creating a job that contains one or more batches. The job specifies which object is being processed and what type of operation is being used. Ingest jobs are defined by CSV, XML, JSON, or binary attachments. Query jobs are defined by a SOQL statement. A job is represented by the JobInfo resource. This resource is used to create a new job, get status for an existing job, and change status for a job. **note:** Salesforce provides an additional API, Bulk API 2.0, which uses the REST API framework to provide similar capabilities to Bulk API. Bulk API 2.0 simplifies the job creation and monitoring process. For more information on Bulk API 2.0, see the [Bulk API 2.0 Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_bulk_v2). 1. [Step One: Create a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-create.md) Create a job by sending a POST request to this URI. The request body identifies the type of object processed in all associated batches. 2. [Step Two: Monitor a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-monitor.md) You can monitor a Bulk API job in Salesforce. The monitoring page tracks jobs and batches created by any client application, including Data Loader or any client application that you write. 3. [Step Three: Close a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-close.md) Close a job by sending a POST request to this URI. The request URI identifies the job to close. When a job is closed, no more batches can be added. 4. [Step Four: Get Job Details](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-get-details.md) Get all details for an existing job by sending a GET request to this URI. 5. [Step Five: Abort a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-abort.md) Abort an existing job by sending a POST request to this URI. The request URI identifies the job to abort. When a job is aborted, no more records are processed. If changes to data have been committed, they aren’t rolled back. # Quick Start: Bulk API 2.0 Get up and running with Bulk API 2.0 by sending a few requests to Salesforce. This Quick Start takes you from setting up a basic environment to inserting, upserting, and querying records using Bulk API 2.0. Experience how to use Bulk API 2.0 via cURL in a free Salesforce Developer Edition org by authenticating and following the examples. - **[Using cURL](https://developer.salesforce.com/docs/platform/api-bulk-v2/example/walkthrough-using-curl.md)** Get to know the formatting used with cURL to place calls to Salesforce orgs. This Quick Start uses cURL examples to issue Bulk API 2.0 calls, but you can use any tool or development environment that can make REST requests. - **[Step 1: Set Up a Salesforce Developer Edition Org](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-quickstart-set-up-org.md)** This Quick Start suggests using a Developer Edition org. Sign up for a Salesforce Developer Edition org before trying Bulk API 2.0 with this Quick Start. - **[Step 2: Authentication](https://developer.salesforce.com/docs/platform/api-bulk-v2/introduction/authentication.md)** The first action in an API-based integration is authenticating requests with your Salesforce org. Bulk API 2.0 and Bulk API use different authentication methods. - **[Step 3: Bulk Insert](https://developer.salesforce.com/docs/platform/api-bulk-v2/example/walkthrough-upload-data.md)** This Bulk API 2.0 example guides you through creating a job, uploading data for the job, notifying Salesforce servers that your upload(s) are complete, checking the status of the processing job, and retrieving the results. - **[Step 4: Bulk Insert with a Multipart Request](https://developer.salesforce.com/docs/platform/api-bulk-v2/example/walkthrough-upload-multipart-data.md)** This Bulk API 2.0 example guides you through creating a job, uploading data for the job, checking the status, and retrieving the results. This example uses a single, multipart request to create the job and upload the data. - **[Step 5: Bulk Upsert](https://developer.salesforce.com/docs/platform/api-bulk-v2/example/walkthrough-upsert.md)** This Bulk API 2.0 example guides you through creating a job, uploading data for the job, notifying Salesforce servers that your upload(s) are complete, checking the status, and retrieving the results. Some of the records exist (update), and some are new records (insert). - **[Step 6: Query Jobs](https://developer.salesforce.com/docs/platform/api-bulk-v2/bulk-query/query-walkthrough.md)** This Bulk API 2.0 example shows you how to create a query job, monitor its progress, and get the job results. # Quick Start: SOAP API Use this quick start to create a sample application in your development environment. **note:** Before you begin building an integration or other client application: - Install your development platform according to its product documentation. - Read through all the steps before beginning this quick start. You may also wish to review the rest of this document to familiarize yourself with terms and concepts. - **[Step 1: Sign up for Salesforce Developer Edition](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-obtain-dev-org.md)** Use Salesforce Developer Edition to develop, stage, and test your API code against sample data. - **[Step 2: Generate or Obtain the Web Service WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-generate-wsdl.md)** To access the Lightning Platform Web service, you need a Web Service Description Language (WSDL) file. The WSDL file defines the Web service that is available to you. - **[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)** - **[Step 4: Walk Through the Sample Code](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-walk-through-code.md)** Once you have imported your WSDL file, you can begin building client applications that use the API. # Quoted String Escape Sequences SOQL defines several escape sequences that are valid in queries so that you can include special characters in your queries. You can escape new lines, carriage returns, tabs, quotes, and more. The escape character for SOQL is the backslash (\\) character. You can use the following escape sequences with SOQL: | Sequence | Meaning | | -------------------------- | -------------------------------------------------------------------------------------------- | | `\n` or `\N` | New line | | `\r` or `\R` | Carriage return | | `\t` or `\T` | Tab | | `\b` or `\B` | Bell | | `\f` or `\F` | Form feed | | `\"` | One double-quote character | | `\'` | One single-quote character | | `\\` | Backslash | | LIKE expression only: `\_` | Matches a single underscore character ( \_ ) | | LIKE expression only:`\%` | Matches a single percent sign character ( % ) | | `\uXXXX` | A Unicode character with XXXX as the code (for example, `\u00e9` represents the é character) | If you use a backslash character in any other context, an error occurs. ## Escaped Character Examples **`SELECT Id FROM Account WHERE Name LIKE 'Ter%'`:** Select all accounts whose name begins with the three character sequence 'Ter'. **`SELECT Id FROM Account WHERE Name LIKE 'Ter\%'`:** Select all accounts whose name exactly matches the four character sequence 'Ter%'. **`SELECT Id FROM Account WHERE Name LIKE 'Ter\%%'`:** Select all accounts whose name begins with the four character sequence 'Ter%' **See Also** - [_Trailhead_: Secure Server-Side Development](https://trailhead.salesforce.com/content/learn/modules/secure-serverside-development) - [_Apex Developer Guide_: SOQL Injection](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/pages_security_tips_soql_injection.htm) # QuoteSaveEvent Notifies subscribers that the process started by the `/actions/standard/quotesaveevent` request is complete. If the process is successful, use this event to learn about the updated quote. If the request isn't successful, use this event to learn about the errors and how to fix them. This object is available in API version 58.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/QuoteSaveEvent` ## Special Access Rules This object is available when Revenue Cloud is enabled. ## Fields ### `CorrelationIdentifier` **Type:** string **Properties:** Nillable **Description:** Reserved for future use. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `QuoteId` **Type:** reference **Properties:** Nillable **Description:** The ID of the quote associated with this event. This field is a relationship field. **Relationship Name:** Quote **Relationship Type:** Lookup **Refers To:** Quote ### `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. ### `RequestIdentifier` **Type:** string **Properties:** Nillable **Description:** The unique ID returned in the `/quotesaveevent` response. Use this ID to identify the event for the specific request. ### `Status` **Type:** picklist **Properties:** Defaulted on create, Nillable, Restricted picklist **Description:** The default value is `NotStarted`. Possible values are: - `CompletedWithPricing` - `CompletedWithTax` - `CompletedWithoutPricing` - `NotStarted` - `PriceCalculationFailed` - `PriceCalculationInProgress` - `PriceCalculationQueued` - `SaveFailedOrIncomplete` - `Saving` - `TaxCalculationFailed` - `TaxCalculationInProgress` - `TaxCalculationSuccess` - `TaxCalculationWaiting` # QuoteToOrderCompletedEvent Notifies subscribers when the `/actions/standard/createOrderFromQuote` REST request is complete. If the request is successful, use this event to learn about the Order record. If the request isn’t successful, use this event to learn about the errors associated with the request. This object is available in API version 56.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/QuoteToOrderCompletedEvent` ## Event Delivery Allocation Enforced No ## Special Access Rules This object is available with Revenue Cloud. |Field|Type|Properties|Description| |-----|----|----------|-----------| |`CorrelationIdentifier`|string|Nillable|Reserved for future use.| |`EventUuid`|string|Nillable|A universally unique identifier (UUID) that identifies a platform event message.| |`HasErrors`|boolean|Defaulted on create|Contains `true` if errors occurred during the process; otherwise `false`. The default value is `false`.| |`OrderId`|string|Nillable|The ID of the order created from the quote. If the process failed, this field is null.| |`OrderNumber`|string|Nillable|The user-friendly, unique number assigned to the order created from the quote.| |`QuoteToOrderErrorDetailEvents`|[QuoteToOrderErrDtlEvent](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/sforce_api_objects_quotetoordererrdtlevent.htm)[]|Nillable|Contains a list of error messages and error codes if the request failed.| |`ReplayId`|string|Nillable|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.| |`RequestIdentifier`|string|Nillable|The unique ID returned in the `actions/standard/createOrderFromQuote` response. Use this ID to identify the event for a specific request.| # QuoteToOrderErrDtlEvent Contains information about any errors that occurred while processing the `/actions/standard/createOrderFromQuote` REST request. One `QuoteToOrderErrDtlEvent` record is created for each error that occurred. This object is included in an `QuoteToOrderCompletedEvent` message. You can't subscribe to `QuoteToOrderErrDtlEvent` directly. This object is available in API version 56.0 and later. ## Supported Calls `describeSObjects()` ## Special Access Rules This object is available when Subscription Management is enabled. ## Fields ### `ErrorCode` **Type:** string **Properties:** Nillable **Description:** The error code; for example, INVALID_INPUT. ### `ErrorMessage` **Type:** textarea **Properties:** Filter, Group, Nillable, Sort **Description:** Information about the error that occurred during processing. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `PrimaryRecordId` **Type:** reference **Description:** The record on which the error occurred; for example, the order that was created by the request. **Relationship Name:** PrimaryRecord **Relationship Type:** Lookup **Refers To:** Asset, Invoice, Order ### `RelatedRecordId` **Type:** reference **Properties:** Nillable **Description:** Optional. A secondary record on which the error occurred; for example, the order item. **Relationship Name:** RelatedRecord **Relationship Type:** Lookup **Refers To:** InvoiceLine, OrderItem ### `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. # Radar Charts Radar charts are like line charts but they use a circular axis instead of a linear grid. Use the `markerType`, `markerSize`, and `markerFill` attributes to set the style, size, and color of the markers. Use the `strokeColor` and `strokeWidth` attributes to set the color and thickness of the connecting lines. Optionally, set `fill=true` to fill the area enclosed by the series, and use `opacity` to make it transparent so that other series remain visible. The `opacity` attribute is a floating point number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque. Here’s an example of a radar chart, and the markup that creates it: ![Radar Chart](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_charting_radar_chart.png) ```visualforce ``` **See Also** - [Chart Colors](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-appearance-colors.md) - [Chart Layout and Annotation](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-appearance-layout.md) # Reactive Apex Wires Reading data via a wire adapter is the “natural” way to access data in Lightning web components. To add a read-only Apex method to a Lightning web component, first import the Apex method from the `@salesforce/apex` module, and then use the `@wire` annotation to connect that method to a property or function in your component. Read the details in [Wire Apex Methods to Lightning Web Components](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_wire_method) in the _Lightning Web Components Developer Guide_. The important things to understand about this method of using Apex are: - `@wire` adapters are **read-only**. - When you use `@wire` adapters, **you** don’t call your Apex method directly. Instead, _the framework_ decides when to call it, when it needs the value of the property or function connected to the `@wire`. This can happen more or less frequently than you expect. - Your Apex method **must not** make server-side changes when called by the `@wire` service. - The result of calling your Apex method is cached on the client. See important details in [Apex Results Are Separate from Other Primed Data](https://developer.salesforce.com/docs/platform/mobile-offline/guide/apex-data-separate-cache.md). These points are standard behavior for Lightning web components. They aren’t specific to the additional mobile and offline features of an offline-enabled mobile app. What _is_ different is the cache. The mobile app saves the results of `@wire` calls to Apex methods in a durable store, instead of an in-memory cache. The durable store is longer-lived than the standard cache used by Lightning web components. The standard cache is designed for performance, rather than offline use. The durable store, in contrast, is designed _specifically_ for offline use. It survives client app restarts, and even device restarts. Data in the durable store is available to provide a result for an Apex method call, even when offline. Again, see considerations in [Apex Results Are Separate from Other Primed Data](https://developer.salesforce.com/docs/platform/mobile-offline/guide/apex-data-separate-cache.md). # Real-Time Event Monitoring Objects Check out the standard platform event and object pairs for Real-Time Event Monitoring. For most platform events used in Real-Time Event Monitoring, corresponding objects store the event data. For more information, see [Real-Time Event Monitoring](https://help.salesforce.com/s/articleView?id=xcloud.real_time_event_monitoring_overview.htm&type=5) in Salesforce Help. **note:** Real-Time Event Monitoring objects sometimes contain sensitive data. Assign object permissions to Real-Time Events accordingly in profiles or permission sets. |Platform Event|Object for Event Storage|Can Be Used in a Transaction Security Policy?| |--------------|------------------------|---------------------------------------------| |[ApiAnomalyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-apianomalyevent.md)|[ApiAnomalyEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-apianomalyeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[ApiEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-apieventstream.md)|[ApiEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-apievent.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[BulkApiResultEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-bulkapiresultevent.md)|[BulkApiResultEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-bulkapiresulteventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[ConcurLongRunApexErrEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-concurlongrunapexerrevent.md)|Not Available| | |[CredentialStuffingEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-credentialstuffingevent.md)|[CredentialStuffingEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-credentialstuffingeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[FileEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-fileevent.md)|[FileEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-fileeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[GuestUserAnomalyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-guestuseranomalyevent.md)|[GuestUserAnomalyEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-guestuseranomalyeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Not Available|[IdentityVerificationEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-identityverificationevent.md)| | |Not Available|[IdentityProviderEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-identityprovidereventstore.md)| | |[LightningUriEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-lightningurieventstream.md)|[LightningUriEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-lightningurievent.md)| | |[ListViewEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-listvieweventstream.md)|[ListViewEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-listviewevent.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[LoginAnomalyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-loginanomalyevent.md)|[LoginAnomalyEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-loginanomalyeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[LoginAsEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-loginaseventstream.md)|[LoginAsEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-loginasevent.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[LoginEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-logineventstream.md)|[LoginEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-loginevent.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[LogoutEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-logouteventstream.md)|[LogoutEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-logoutevent.md)| | |[MobileEmailEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-mobileemailevent.md)|Not Available| | |[MobileEnforcedPolicyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-mobileenforcedpolicyevent.md)|Not Available| | |[MobileScreenshotEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-mobilescreenshotevent.md)|Not Available| | |[MobileTelephonyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-mobiletelephonyevent.md)|Not Available| | |[PermissionSetEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-permissionsetevent.md)|[PermissionSetEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-permissionseteventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[ReportAnomalyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-reportanomalyevent.md)|[ReportAnomalyEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-reportanomalyeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[ReportEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-reporteventstream.md)|[ReportEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-reportevent.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[SessionHijackingEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-sessionhijackingevent.md)|[SessionHijackingEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-sessionhijackingeventstore.md)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |[UniversalAnomalyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-universalanomalyevent.md)|[UniversalAnomalyEventStore](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-universalanomalyeventstore.md)| | |[UriEventStream](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-urieventstream.md)|[UriEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-urievent.md)| | **note:** Real-Time Event monitoring objects that were introduced as part of the beta release in API version 46.0 follow a naming convention that is no longer used in later API versions. In particular: - The name format of a platform event object was `ObjectNameEventStream`. - The name format of the corresponding big object used for storage was `ObjectNameEvent`. New event objects introduced after API version 46.0 use the following standard platform event naming convention. - The name format of a platform event object is `ObjectNameEvent`. - The name format of the corresponding object used for storage is `ObjectNameEventStore`. # RealtimeAlertEvent Notifies subscribers of Amazon CloudWatch alarm events from your Service Cloud Voice Amazon Connect instance. This object is available in API version 54.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/RealtimeAlertEvent` ## Special Access Rules Accessing this object requires Service Cloud Voice with Amazon Connect enabled. ## Event Delivery Allocation Enforced Yes ## Fields ### `Description` **Type:** string **Properties:** None **Description:** Required. Description of the alert fired. ### `EventDateTime` **Type:** datetime **Properties:** None **Description:** Date and time when the alert occurred. For example: `2020-12-18 21:59:48`. ### `Name` **Type:** string **Properties:** None **Description:** Required. Name of the alert fired. ### `Payload` **Type:** string **Properties:** None **Description:** More information and data associated with the alert. ### `Severity` **Type:** string **Properties:** None **Description:** Required. Severity of the triggered alarm. Possible values: Values are Critical, Warning, or Information. When using Amazon CloudWatch with Service Cloud Voice, the following alarm states map to severity values: Values are ALARM maps to Critical, INSUFFICIENT_DATA maps to Warning, or OK maps to Information. ### `Source` **Type:** string **Properties:** None **Description:** Required. The source of the alert. For example, this value can be the service name: `AWS Cloudwatch`. ## Usage The following example shows how to process RealtimeAlert events. This Apex trigger example fires when a platform event message is published and creates a Chatter post on the admin profile with event details. ```apex trigger RealtimeAlertEventTrigger on RealtimeAlertEvent (after insert) { Id profileId = [select Id from User where User.Profile.Name = 'System Administrator' limit 1].Id; for(RealtimeAlertEvent e : trigger.new) { Feeditem Post = New Feeditem(); Post.ParentId= profileId; Post.Body = 'Alert occurred in the service: ' + e.Source + '\n' + 'Name: ' + e.Description + '\n' + 'Severity: ' + e.EventDateTime + '\n' + 'Payload: ' + e.Payload + '\n' + 'EventDate: ' + e.EventDateTime + '\n' + 'Description: ' + e.Name + '\n'; insert Post; } } ``` ## Example The code example displays as a Chatter post that contains the following: ```nolang Alert occurred in the service: aws cloudwatch alarm Name: alert description Severity: 2021-11-05 11:11:11 Payload: payload EventDate: 2021-11-05 11:11:11 Description: alert name ``` # Reassign Approval Work Item Action Reassign an approval work item that hasn't been completed. You can also add comments about why the approval admin reassigned the approval work item. This action also validates if a user has required permissions to reassign an approval work item and update the assignee. Keep these considerations in mind when you use this invocable action. - The user must have the Approval Admin user permission. - The status of the approval work item must be in `Assigned` status. This action is available in API version 62.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v68.0/actions/standard/reassignApprovalWorkItem` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`approvalWorkItemId`|string|Required. ID of the approval work item to be reassigned.| |`assigneeId`|string|Required. ID of the user, group, or queue to reassign the approval work item to.| |`comments`|string|Comments entered by the approval admin about why they reassigned the approval work item.| ## Outputs None. ## Example **POST** Here's a sample request for the Reassign Approval Work Item action. ```nolang { "inputs": [ { "approvalWorkItemId": "9jRDU00000015C22AI", "assigneeId": "005DU000000I3zHYAS", "comments": "Needs to be reviewed." } ] } ``` Here's a sample response for the Reassign Approval Work Item action. ```nolang { "actionName": "reassignApprovalWorkItem", "errors": null, "invocationId": null, "isSuccess": true, "outcome": null, "outputValues": null, "sortOrder": -1, "version": 1 } ``` # Recall Approval Submission Action Recall an approval submission that isn't completed. You can also add comments that the submitter or approval admin made the recall. This action also validates if a user has required permissions to recall an approval submission. Keep these considerations in mind when you use this invocable action. - The user must have the Approval Admin user permission. - The user must also be a submitter of this approval submission. - The status of the approval submission must be in `In progress` or `Suspended` status. This action is available in API version 62.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v68.0/actions/standard/recallApprovalSubmission` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`approvalSubmissionId`|string|Required. ID of the approval submission to be recalled.| |`comments`|string|Comments entered by the approval admin or approval submitter about why they recalled the approval submission.| ## Outputs None. ## Example **POST** Here's a sample request for the Recall Approval Submission action. ```nolang { "inputs": [ { "approvalSubmissionId": "9iPxx00000001lhEBA", "comments": "Recall comments." } ] } ``` Here's a sample response for the Recall Approval Submission action. ```nolang { "actionName": "recallApprovalSubmission", "errors": null, "invocationId": null, "isSuccess": true, "outcome": null, "outputValues": null, "sortOrder": -1, "version": 1 } ``` # Recent List Views Returns the list of recently used list views for the given sObject type. This resource is available in REST API version 32.0 and later. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/listviews/recent` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters:** None ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/listviews/recent -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang { "done" : true, "listviews" : [ { "describeUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCNMA0/describe", "developerName" : "MyAccounts", "id" : "00BD0000005WcCNMA0", "label" : "My Accounts", "resultsUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCNMA0/results", "soqlCompatible" : true, "url" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCNMA0" }, { "describeUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcBeMAK/describe", "developerName" : "NewThisWeek", "id" : "00BD0000005WcBeMAK", "label" : "New This Week", "resultsUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcBeMAK/results", "soqlCompatible" : true, "url" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcBeMAK" }, { "describeUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCFMA0/describe", "developerName" : "AllAccounts", "id" : "00BD0000005WcCFMA0", "label" : "All Accounts", "resultsUrl" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCFMA0/results", "soqlCompatible" : true, "url" : "/services/data/v68.0/sobjects/Account/listviews/00BD0000005WcCFMA0" } ], "nextRecordsUrl" : null, "size" : 3, "sobjectType" : "Account" } ``` # Recently Viewed Items Gets the most recently accessed items that were viewed or referenced by the current user. Salesforce stores information about record views in the interface and uses it to generate a list of recently viewed and referenced records, such as in the sidebar and for the auto-complete options in search. This resource only accesses most recently used item information. If you want to modify the list of recently viewed items, you must update recently viewed information directly by using a SOQL Query with a `FOR VIEW` or `FOR REFERENCE` clause. **note:** The API response filters and displays recent records based on the permissions of the token or session ID user. **URI:** `/services/data/vXX.X/recent` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`limit`|An optional limit that specifies the maximum number of records to be returned. If this parameter is not specified, the default maximum number of records returned is the maximum number of entries in RecentlyViewed, which is 200 records in total.| ## Example - For an example of retrieving a list of recently viewed items, see [View Recently Viewed Records](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-see-recently-viewed.md). - For an example of setting records as recently viewed, see [Mark Records as Recently Viewed](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-mark-records-as-recently-viewed.md). # Record The Record object is a JSON-formatted object that contains information about the object on which the canvas app appears. This could be a standard object like `Account` or a custom object like `Warehouse__c`. If the canvas app doesn’t appear on an object page or in the publisher or feed associated with an object, then the Record object is empty. This object contains the [Attributes](https://developer.salesforce.com/docs/platform/canvas-framework/guide/attributes-object.md) object. |Field|Description| |-----|-----------| |`Id`|The ID of the related object. For example, if the canvas app appears on an Account page, this field contains the `AccountId`.| If the canvas app appears on a Visualforce page through use of the `` component, and that Visualforce page is associated with an object (placed on the page layout, for example), you can use the `entityFields` attribute on the component to return specific fields or all fields from the related object. The following code snippet shows an example of the Record object returned from a canvas app that appears on an Account page. In this example, the Phone, Fax, and BillingCity fields were specified in the `entityFields` attribute. ```nolang "record":{ "attributes":{ "type":"Account", "url":"/services/data/v68.0/sobjects/Account/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO", "Phone":"(555) 555-5555", "Fax":"(555) 555-5555", "BillingCity":"Seattle" } ``` - **[Attributes](https://developer.salesforce.com/docs/platform/canvas-framework/guide/attributes-object.md)** - **[Record Object Examples](https://developer.salesforce.com/docs/platform/canvas-framework/guide/record-object-examples.md)** These code examples demonstrate how the Record object contains different information depending on whether your canvas app appears in the publisher or the feed. **See Also** - [Environment](https://developer.salesforce.com/docs/platform/canvas-framework/guide/environment-object.md) - [Attributes](https://developer.salesforce.com/docs/platform/canvas-framework/guide/attributes-object.md) - [Record Object Examples](https://developer.salesforce.com/docs/platform/canvas-framework/guide/record-object-examples.md) - [Returning Fields in the Record Object](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-vf-component-record-fields.md) # Record Changes To perform more advanced tasks using `force:recordData` when the record changes, handle the `recordUpdated` event. You can handle record loaded, updated, and deleted changes, applying different actions to each change type. If a component performs logic that’s specific to the record data, it must run that logic again when the record changes. A common example is a business process in which the actions that apply to a record change depending on the record’s values. For example, different actions apply to opportunities at different stages of the sales cycle. **note:** Lightning Data Service notifies listeners about data changes only if the changed fields are the same as in the listener’s fields or layout. The example shown here declares that your component handles the `recordUpdated` event. To improve performance, we recommend using the `fields` attribute to query only the fields you need. Use `layoutType` only if you want the administrator, not the component, to control the fields that are provisioned. The component must handle receiving every field that is assigned to the layout for the context user. ```nolang ``` Implement an action handler that handles the change. ```javascript ({ recordUpdated: function(component, event, helper) { var changeType = event.getParams().changeType; if (changeType === "ERROR") { /* handle error; do this first! */ } else if (changeType === "LOADED") { /* handle record load */ } else if (changeType === "REMOVED") { /* handle record removal */ } else if (changeType === "CHANGED") { /* handle record change */ } }) ``` When loading a record in edit mode, the record isn’t automatically updated to prevent edits currently in progress from being overwritten. To update the record, use the `reloadRecord` method in the action handler. ```nolang ``` ```javascript ({ recordUpdated : function(component, event, helper) { var changeType = event.getParams().changeType; if (changeType === "ERROR") { /* handle error; do this first! */ } else if (changeType === "LOADED") { /* handle record load */ } else if (changeType === "REMOVED") { /* handle record removal */ } else if (changeType === "CHANGED") { /* handle record change; reloadRecord will cause you to lose your current record, including any changes you’ve made */ component.find("forceRecord").reloadRecord();} } }) ``` # Record Count Lists information about object record counts in your organization. This resource is available in REST API version 40.0 and later for API users with the “View Setup and Configuration” permission. The returned record count is a cached snapshot in time that may not accurately represent the number of records in the object at the time of the request. The record count value is updated automatically at variable time intervals, and there are no fixed schedules for these updates. It doesn’t include the following types of records: - Deleted records in the recycle bin - Archived records - Associated objects such as ChangeEvent, Feed, History, OwnerSharingRule, and Share objects To get an accurate count, use the SOQL query `SELECT count() FROM sObject`. Results are limited to records visible to the user executing the query. ## Syntax **URI:** `/services/data/vXX.X/limits/recordCount?sObjects=objectList` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`sObjects`|A comma-delimited list of object names. If a listed object isn’t found in the org, it’s ignored and not returned in the response. This parameter is optional. If this parameter isn’t provided, the resource returns record counts for all objects in the org.| **Response body:** [Record Count Response Body](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-record-count.md#record-count-response-body) ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/limits/recordCount?sObjects=Account,Contact -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang { "sObjects" : [ { "count" : 3, "name" : "Account" }, { "count" : 10, "name" : "Contact" } ] } ``` # Record Count Response Body Describes the result of a Record Count request. ## Record Count Results **Properties** |Name|Type|Description| |----|----|-----------| |`sObjects`|[Record Count sObject Result](#record-count-sobject-result)[]|Collection of sObject record count results. The order of objects in the collection is not guaranteed to match the order of objects in the request.| **JSON example** ```nolang { "sObjects" : [ { "count" : 3, "name" : "Account" }, { "count" : 10, "name" : "Contact" } ] } ``` ## Record Count sObject Result **Properties** |Name|Type|Description| |----|----|-----------| |`count`|Integer|The number of records for the object in the org. This is an approximate count and does not include soft-deleted or archived records.| |`name`|String|The name of the object.| **JSON example** ```nolang { "count" : 10, "name" : "Contact" } ``` # Record Object Examples These code examples demonstrate how the Record object contains different information depending on whether your canvas app appears in the publisher or the feed. ## Canvas App in the Publisher If your canvas app appears in the publisher, the Record object contains different information depending on whether the publisher appears on a user record, a group record, or an object record. - User Record - : The Record object `Id` is the `User.Id` and the `Type` is `User`. ```nolang "record":{ "attributes":{ "type":"User", "url":"/services/data/v68.0/sobjects/User/001xx000003DGWiABC" }, "Id":"001xx000003DGWiABC" } ``` - Group Record - : The Record object `Id` is the `CollaborationGroup.Id` and the `Type` is `CollaborationGroup`. ```nolang "record":{ "attributes":{ "type":"CollaborationGroup", "url":"/services/data/v68.0/sobjects/CollaborationGroup/001xx000003DGWiXYZ" }, "Id":"001xx000003DGWiXYZ" } ``` - Object Record - : The Record object `Id` is the object `Id` and the `Type` is the object name, for example, `Account`. ```nolang "record":{ "attributes":{ "type":"Account", "url":"/services/data/v68.0/sobjects/Account/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO" } ``` ## Canvas App in the Feed If your canvas app appears in the feed, the Record object always contains the feed item information whether the feed is on a user record, a group record, or an object record. The Record object `Id` is the `FeedItem.Id` and the `Type` is `FeedItem`. ```nolang "reoord":{ "attributes":{ "type":"FeedItem", "url":"/services/data/v68.0/sobjects/FeedItem/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO" } ``` # Record Tax Reversal Action Reverses the recorded tax transactions in an external system, such as Stripe, after an order is returned or canceled. This action is available in API version 62.0 and later for users with these licenses: - B2B Commerce, or D2C Commerce - Salesforce Order Management Only store administrators can access this action. ## Supported REST HTTP Methods **URI:** `/services/data/vXX.X/actions/standard/recordTaxReversal` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`taxReversalInfos`|Apex-defined|Required. A list of Apex `commercestoretax__TaxReversalInfo` records containing details about the tax transactions for the order that was returned or canceled.| ## Outputs |Output|Type|Description| |------|----|-----------| |`taxReversalResult`|Apex-defined|An Apex `commercestoretax__TaxReversalResult` record containing details about each tax transaction in the reversal request. The details include whether each reversal was successful and, if not, any error messages returned.| ## Example **Sample Request** ```nolang { "inputs": [ { "taxReversalInfos": { "taxReversalInfoList": [ { "orderItemSummaryId": "10uxx0000004EdmAAE", "quantity": 1, "amount": -10, "taxAmount": 1.0 } ] } } ] } ``` **Sample Response** ```nolang [ { "actionName": "RECORD_TAX_REVERSAL", "errors": null, "invocationId": null, "isSuccess": true, "outputValues": { "taxReversalResult": { "success": true, "resultItems": [ { "transactionReferenceNumber": "tax_1PcknrITDqIkouLURfR4pNAM", "success": true, "orderItemSummaryId": "10uxx0000004EicAAE", "lineItemReference": tax_li_QZM99en1lXKf9s, "errorMessage": null } ], "errorMessage": null } }, "sortOrder": -1, "version": 1 } ] ``` # Record Tax Transaction Action Records tax transactions from an order summary to an external system such as Stripe. This action is available in API version 62.0 and later with these licenses: - B2B Commerce, or D2C Commerce - Salesforce Order Management Only store administrators can access this action. ## Supported REST HTTP Methods **URI:** `/services/data/vXX.X/actions/standard/recordTaxTransaction` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`orderSummaryId`|string|Required. The ID of the order summary to record tax transaction for.| ## Outputs |Output|Type|Description| |------|----|-----------| |`taxTransactionResult`|Apex-defined|An `commercestoretax__TaxTransactionResult` record that contains details about the tax transactions recorded.| ## Example **Sample Request** ```nolang { "inputs": [ { "orderSummaryId": "1Osxx0000004CVcCAM" } ] } ``` **Sample Response** ```nolang [ { "actionName": "RECORD_TAX_TRANSACTION", "errors": null, "invocationId": null, "isSuccess": true, "outputValues": { "taxTransactionResult": { "success": true, "resultItems": [ { "transactionReferenceNumber": "tax_1PcknrITDqIkouLURfR4pNAM", "success": true, "orderItemSummaryId": "10uxx0000004EicAAE", "errorMessage": null, "calculationReferenceNumber": null }, { "transactionReferenceNumber": "tax_1PcknrITDqIkouLURfR4pNAM", "success": true, "oderItemSummaryId": "10uxx0000004EibAAE", "errorMessage": null, "calculationReferenceNumber": null } ], "orderSummaryId": "1Osxx0000004CVc", "errorMessage": null } }, "sortOrder": -1, "version": 1 } ] ``` # Recurring Activities The activity series record is tracked in a single change event. Each occurrence in the series is tracked by an individual change event. ## Example These two change events are delivered to a Pub/Sub API client when creating a recurring calendar event. The first change event is for the event series record, which represents the recurrence pattern, with `GroupEventType` set to 3. The second change event is for the first occurrence. The `ActivityDateTime` and `ActivityDate` are in Epoch time. The other occurrences are omitted in this example. ```json // Change event generated for the event series record. { "ChangeEventHeader": { "entityName": "Event", "recordIds": [ "00UZM000000wuBw2AI" ], "changeType": "CREATE", "changeOrigin": "com/salesforce/api/soap/61.0;client=SfdcInternalAPI/", "transactionKey": "000a48c7-f73c-5d0b-7650-123ab3a20e70", "sequenceNumber": 1, "commitTimestamp": 1714408223000, "commitNumber": 72779532308, "commitUser": "005ZM000000M6o1YAC", "nulledFields": [], "diffFields": [], "changedFields": [] }, "WhoId": null, "WhatId": null, "Subject": "Product Planning", "Location": "San Francisco", "IsAllDayEvent": false, "ActivityDateTime": 1715014800000, "ActivityDate": 1714953600000, "DurationInMinutes": 60, "Description": "Let's meet to discuss product requirements.", "AccountId": null, "OwnerId": "005ZM000000M6o1YAC", "Type": null, "IsPrivate": false, "ShowAs": "Busy", "IsChild": false, "IsGroupEvent": false, "GroupEventType": "3", "CreatedDate": 1714408223000, "CreatedById": "005ZM000000M6o1YAC", "LastModifiedDate": 1714408223000, "LastModifiedById": "005ZM000000M6o1YAC", "RecurrenceActivityId": null, "IsRecurrence": false, "RecurrenceStartDateTime": null, "RecurrenceEndDateOnly": null, "RecurrenceTimeZoneSidKey": null, "RecurrenceType": null, "RecurrenceInterval": null, "RecurrenceDayOfWeekMask": null, "RecurrenceDayOfMonth": null, "RecurrenceInstance": null, "RecurrenceMonthOfYear": null, "ReminderDateTime": null, "IsReminderSet": false, "IsRecurrence2Exclusion": false, "Recurrence2PatternText": "RRULE:FREQ=WEEKLY;BYDAY=MO;WKST=SU;INTERVAL=1;COUNT=13", "Recurrence2PatternVersion": "1", "ActivityRecurrence2Id": "828ZM0000000001YAA", "ActivityRecurrence2ExceptionId": null } // Change event generated for the first occurrence. { "ChangeEventHeader": { "entityName": "Event", "recordIds": [ "00UZM000000wuBx2AI" ], "changeType": "CREATE", "changeOrigin": "com/salesforce/api/soap/61.0;client=SfdcInternalAPI/", "transactionKey": "000a48c7-f73c-5d0b-7650-123ab3a20e70", "sequenceNumber": 2, "commitTimestamp": 1714408224000, "commitNumber": 72779532308, "commitUser": "005ZM000000M6o1YAC", "nulledFields": [], "diffFields": [], "changedFields": [] }, "WhoId": null, "WhatId": null, "Subject": "Product Planning", "Location": "San Francisco", "IsAllDayEvent": false, "ActivityDateTime": 1715014800000, "ActivityDate": 1714953600000, "DurationInMinutes": 60, "Description": "Let's meet to discuss product requirements.", "AccountId": null, "OwnerId": "005ZM000000M6o1YAC", "Type": null, "IsPrivate": false, "ShowAs": "Busy", "IsChild": false, "IsGroupEvent": false, "GroupEventType": "0", "CreatedDate": 1714408224000, "CreatedById": "005ZM000000M6o1YAC", "LastModifiedDate": 1714408224000, "LastModifiedById": "005ZM000000M6o1YAC", "RecurrenceActivityId": null, "IsRecurrence": false, "RecurrenceStartDateTime": null, "RecurrenceEndDateOnly": null, "RecurrenceTimeZoneSidKey": null, "RecurrenceType": null, "RecurrenceInterval": null, "RecurrenceDayOfWeekMask": null, "RecurrenceDayOfMonth": null, "RecurrenceInstance": null, "RecurrenceMonthOfYear": null, "ReminderDateTime": null, "IsReminderSet": false, "IsRecurrence2Exclusion": false, "Recurrence2PatternText": "RRULE:FREQ=WEEKLY;BYDAY=MO;WKST=SU;INTERVAL=1;COUNT=13", "Recurrence2PatternVersion": "1", "ActivityRecurrence2Id": "828ZM0000000001YAA", "ActivityRecurrence2ExceptionId": null } ``` # Redirecting to a Standard Object List Page For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects. Create a Visualforce page with the following markup: ```visualforce ``` The user will see a page that resembles the following: ![An Account detail page](https://developer.salesforce.com/media/salesforce-pages-developers-guide/vf_account_list.png "Overriding the Account Detail Page") The Visualforce page can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For example: ```visualforce ``` # Reference The following table lists supported REST resources in the API and provides a brief description for each. In each case, the URI for the resource follows the base URI, `https://MyDomainName.my.salesforce.com`. For example, to retrieve basic information about an Account object in version 68.0 use `https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account`. For information about standard and custom objects that you access with sObject resources, see [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/). Some of these resources are only available if you have the corresponding package installed or have the corresponding feature enabled. **note:** Some parts of request URIs are case-sensitive, such as IDs. Other parts of URIs aren't case-sensitive, such as object and field names. If your requests aren't successful, check that your URI has the right letter cases by comparing the URI to the reference and examples in this guide. |Resource Name|URI and Description| |-------------|-------------------| |[Versions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-versions.md)|`/services/data` Lists summary information about each Salesforce version currently available, including the version, label, and a link to each version's root.| |[Resources by Version](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-discoveryresource.md)|`/services/data/vXX.X` Lists available resources for the specified API version, including resource name and URI.| |[Invocable Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-actions-invocable.md)|`/services/data/vXX.X/actions/standard` `/services/data/vXX.X/actions/custom` Use actions to add more functionality to your applications. Choose from standard actions, such as posting to Chatter or sending email, or create actions based on your company’s needs.| |Analytics(Accesses Reports and Dashboards REST API)|`/services/data/vXX.X/analytics` Accesses Reports and Dashboards REST API resources. See the [Salesforce Reports and Dashboards REST API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/sforce_analytics_rest_api_intro.htm).| |[Get AppMenu Types](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-appmenu-get.md)|`/services/data/vXX.X/appMenu/` Accesses App Menu types in the Salesforce app dropdown menu.| |[AppMenu Items](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-appmenu.md)|`/services/data/vXX.X/appMenu/AppSwitcher` Accesses App Menu items from the Salesforce app dropdown menu.| |[AppMenu Mobile Items](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-appmenu-mobile-web.md)|`/services/data/vXX.X/appMenu/Salesforce1/` Accesses App Menu items from the Salesforce mobile app for Android and iOS and the mobile web navigation menu.| |Asset Management|`/services/data/vXX.X/asset-management` Makes make lifecycle-managed asset data available for sales and account reps to view in Lightning Experience. See [Customer Asset Lifecycle Management](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/features_asset_lifecycle_use_cases.htm) in the *Connect REST API Developer Guide*.| |Async Queries|`/services/data/vXX.X/async-queries` Submits a SOQL query to be processed asynchronously. See [Async Query](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_async_queries.htm) in the *Connect REST API Developer Guide* and [Async SOQL Use Cases](https://developer.salesforce.com/docs/atlas.en-us.bigobjects.meta/bigobjects/async_query_examples.htm) in the *Big Objects Implementation Guide*.| |Chatter(Connect REST API)|`/services/data/vXX.X/chatter` Accesses Chatter features in the Connect REST API. See [Chatter REST API Resources](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_chatter_resources_overview.htm) in the *Connect REST API Developer Guide*.| |Commerce(Place Order REST API)|`/services/data/vXX.X/commerce` Accesses features in the Place Order REST API. See the [Place Order REST API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_placeorder.meta/api_placeorder/sforce_placeorder_rest_api_intro.htm).| |[Compact Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-compact-layouts.md)|`/services/data/vXX.X/compactLayouts?q=objectList` Returns a list of compact layouts for multiple objects.| |[Composite](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-composite.md)|`/services/data/vXX.X/composite` Executes a series of REST API requests in a single POST request, or retrieves a list of other composite resources with a GET request.| |[Composite Batch](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-batch.md)|`/services/data/vXX.X/composite/batch` Executes up to 25 subrequests in a single request.| |[Using Composite Graphs](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-graph-introduction.md)|`/services/data/vXX.X/composite/graph` Provides an enhanced way to perform composite requests.| |[sObject Tree](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-sobject-tree.md)|`/services/data/vXX.X/composite/tree` Creates one or more sObject trees with root records of the specified type. An sObject tree is a collection of nested, parent-child records with a single root record.| |[sObject Collections](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-sobjects-collections.md)|`/services/data/vXX.X/composite/sobjects` Executes actions on multiple records in one request.| |Connect REST API|`/services/data/vXX.X/connect` Accesses features in the Connect REST API. See the [Connect REST API Resources](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_overview.htm) in the *Connect REST API Developer Guide*.| |Financial Services|`/services/data/vXX.X/connect/financialservices` Accesses Financial Services objects. See the [Financial Services Cloud Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.financial_services_cloud_object_reference.meta/financial_services_cloud_object_reference/fsc_api_access_and_usage.htm).| |Health Cloud|`/services/data/vXX.X/connect/health/care-services` Accesses Health Cloud objects. See the [Health Cloud Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.health_cloud_object_reference.meta/health_cloud_object_reference/object_ref_overview.htm).| |Manufacturing|`/services/data/vXX.X/connect/manufacturing` Accesses Manufacturing Cloud objects. See the [Manufacturing Cloud Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.mfg_api_devguide.meta/mfg_api_devguide/mfg_api_overview.htm).| |Consumer Goods|`/services/data/vXX.X/connect/object-detection` `/services/data/vXX.X/connect/visit/recommendations` Accesses the Consumer Goods Business API. See the [Consumer Goods Cloud Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.retail_api.meta/retail_api/sforce_api_objects_retail_overview.htm).| |[Consent](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-consent.md)|`/services/data/vXX.X/consent` Tracks users’ consent preferences.| |Contact Tracing|`/services/data/vXX.X/contact-tracing` Tracks health contacts. See the [Emergency Response Management for Public Health Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.ph_api.meta/ph_api/erm_dev_guide_overview.htm).| |Dedupe|`/services/data/vXX.X/dedupe` Lists duplicate resources, job definitions, and jobs. See the [Connect REST API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/intro_what_is_chatter_connect.htm).| |Domino|`/services/data/vXX.X/domino` For internal use only.| |Eclair(geodata)|`/services/data/vXX.X/eclair` Accesses geodata definitions. See [Charts Geodata Resource](https://developer.salesforce.com/docs/atlas.en-us.bi_dev_guide_rest.meta/bi_dev_guide_rest/bi_resources_eclair_geodata_id.htm) in the *Analytics REST API Developer Guide*.| |Email Connect|`/services/data/vXX.X/emailConnect` For internal use only.| |[Platform Event Schema by Schema ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-event-eventschema.md)|`/services/data/vXX.X/event/eventSchema/schemaId` Gets the definition of a platform event in JSON format for a schema ID. This resource is available in REST API version 40.0 and later.| |Folders|`/services/data/vXX.X/folders` Use the Analytics Folders API to perform operations on report and dashboard folders. See [Folders](https://developer.salesforce.com/docs/atlas.en-us.api_analytics.meta/api_analytics/analytics_api_folders_reference_resource.htm) in the *Reports and Dashboards REST API Developer Guide*.| |Jobs(Bulk API 2.0)|`/services/data/vXX.X/jobs` Accesses jobs in the Bulk API 2.0. See the [Bulk API 2.0 and Bulk API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/asynch_api_intro.htm).| |jsonxform(Analytics REST API)|`/services/data/vXX.X/jsonxform` Tests the results of a rule in a Tableau template. See [Rules Testing with jsonxform/transformation endpoint](https://developer.salesforce.com/docs/atlas.en-us.bi_dev_guide_wave_templates.meta/bi_dev_guide_wave_templates/bi_templatesdev_jsonxform_transformation.htm) the *Analytics Templates Developer Guide*.| |Knowledge Management|`/services/data/vXX.X/knowledgeManagement` Accesses Salesforce Knowledge features. See the [Knowledge Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.knowledge_dev.meta/knowledge_dev/knowledge_development_intro.htm).| |Licensing|`/services/data/vXX.X/licensing` For internal use only.| |[Limits](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-limits.md)|`/services/data/vXX.X/limits` Lists information about limits in your org. For each limit, this resource returns the maximum allocation and the remaining allocation based on usage.| |[Record Count](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-record-count.md)|`/services/data/vXX.X/limits/recordCount` Lists information about object record counts in your organization.| |[Salesforce Surveys Translation Resources](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-survey-translation.md)|`/services/data/vXX.X/localizedvalue` Use REST APIs to translate survey fields, view, update, or delete translated survey fields. The translated values of surveys fields are stored in Flow fields.| |Metadata|`/services/data/vXX.X/metadata` Accesses features in the Metadata API. See the [Metadata API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/metadata.htm).| |[Parameterized Search](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-parameterized.md#parameterized-search)|`/services/data/vXX.X/parameterizedSearch/?q=searchString` Executes a simple REST search using parameters instead of a SOSL clause. Indicate parameters in the URI with the GET method. Or, use the POST method to create complex searches in a request body.| |Payments|`/services/data/vXX.X/payments` For internal use only.| |[Process Approvals](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-process-approvals.md)|`/services/data/vXX.X/process/approvals` Accesses all approval processes. Can also be used to submit a particular record if that entity supports an approval process and one has already been defined. Records can be approved and rejected if the current user is an assigned approver.| |[Process Rules](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-process-rules.md)|`/services/data/vXX.X/process/rules` Accesses a list of all active workflow rules. Use the GET method to retrieve records or fields. Use the HEAD method to retrieve information in HTTP headers. Use the POST method to trigger all active workflow rules.| |[Query](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-query.md) (SOQL)|`/services/data/vXX.X/query/?q=soql` Executes the specified SOQL query.| |[QueryAll](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-queryall.md) (SOQL)|`/services/data/vXX.X/queryAll/?q=soql`Executes the specified SOQL query. Results can include deleted, merged, and archived records.| |[Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md)|`/services/data/vXX.X/quickActions` Returns a list of global quick actions and their types, as well as custom fields and objects that appear in the Chatter feed.| |[Recently Viewed Items](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-recent-items.md)|`/services/data/vXX.X/recent` Gets the most recently accessed items that were viewed or referenced by the current user.| |[Salesforce Scheduler Resources](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-ls-intro.md)|`/services/data/vXX.X/scheduling/` Accesses Scheduler REST APIs to get appointment time slots or available service resources based on work type groups and service territories.| |[Search](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search.md) (SOSL)|`/services/data/vXX.X/search/?q=sosl` Executes the specified SOSL search. The search string must be URL-encoded.| |[Search Scope and Order](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-scope-order.md)|`/services/data/vXX.X/search/scopeOrder` Returns an ordered list of objects in the default global search scope of a logged-in user. Global search keeps track of which objects the user interacts with and how often and arranges the search results accordingly. Objects used most frequently appear at the top of the list.| |[Search Suggested Queries](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-suggest-queries.md)|`/services/data/vXX.X/search/​suggestSearchQueries​?q=searchString​&language=languageOfQuery` Returns a list of suggested searches based on the user’s query string text matching searches that other users have performed in Salesforce Knowledge. Provides a way to improve search effectiveness, before the user performs a search. This resource is available in REST API version 30.0 and later.| |[Search Suggested Article Title Matches](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-suggest-title-matches.md)|`/services/data/vXX.X/search/suggestTitleMatches​?q=searchString​&language=articleLanguage&publishStatus=articlePublicationStatus` Returns a list of Salesforce Knowledge article titles that match the user’s search query string. Provides a shortcut to navigate directly to likely relevant articles before the user performs a search.| |[Search Result Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-layouts.md)|`/services/data/vXX.X/searchlayout/​?q=commaDelimitedObjectList` Returns search result layout information for the objects in the query string. For each object, this call returns the list of fields displayed on the search results page as columns, the number of rows displayed on the first page, and the label used on the search results page.| |Service Templates|`/services/data/vXX.X/serviceTemplates` For internal use only.| |Smart Data Discovery(Insights API)|`/services/data/vXX.X/smartdatadiscovery` Uses the Insights API to embed insights into a website, application, or dashboard. See [Get Descriptive and Diagnostic Insights Programmatically](https://help.salesforce.com/s/articleView?id=bi_edd_insight_api.htm).| |[Describe Global](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-describeglobal.md)|`/services/data/vXX.X/sobjects` In addition, it provides the org encoding, as well as the maximum batch size permitted in queries. For more information on encoding, see [Internationalization and Character Sets](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/implementation_considerations.htm#sforce_api_other_internationalization).| |[Platform Event Schema by Event Name](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-eventschema.md)|`/services/data/vXX.X/sobjects/eventName/eventSchema` Gets the definition of a platform event in JSON format for an event name.| |[Lightning Exit by Page Metrics](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-exitbypagemetrics.md)|`/services/data/vXX.X/sobjects/LightningExitByPageMetrics` Returns frequency metrics about the standard pages within which users switched from Lightning Experience to Salesforce Classic.| |[Lightning Toggle Metrics](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-togglemetrics.md)|`/services/data/vXX.X/sobjects/LightningToggleMetrics` Returns details about users who switched between Salesforce Classic and Lightning Experience.| |[Lightning Usage by App Type](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-usagebyapptypemetrics.md)|`/services/data/vXX.X/sobjects/LightningUsageByAppTypeMetrics` Returns the total number of Lightning Experience and Salesforce Mobile users. This resource is available in REST API version 44.0 and later.| |[Lightning Usage by Browser](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-usagebybrowsermetrics.md)|`/services/data/vXX.X/sobjects/LightningUsageByBrowserMetrics` Returns Lightning Experience usage results grouped by browser instance.| |[Lightning Usage by FlexiPage](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-usagebyflexipagemetrics.md)|`/services/data/vXX.X/sobjects/LightningUsageByFlexiPageMetrics` Returns details about the custom pages viewed most frequently in Lightning Experience.| |[Lightning Usage by Page](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-lightning-usagebypagemetrics.md)|`/services/data/vXX.X/sobjects/LightningUsageByPageMetrics` Represents standard pages users viewed most frequently in Lightning Experience.| |[sObject PlatformAction](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-platformaction.md)|`/services/data/vXX.X/sobjects/PlatformAction` Queries for actions displayed in the UI, given a user, a context, device format, and a record ID. Examples include standard and custom buttons, quick actions, and productivity actions.| |[sObject Relevant Items](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-relevant-items.md)|`/services/data/vXX.X/sobjects/relevantItems` Gets the current user’s most relevant items. Relevant items include records for objects in the user’s global search scope and also most recently used (MRU) objects.| |[sObject Basic Information](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-basic-info.md)|`/services/data/vXX.X/sobjects/sObject` Retrieves basic metadata for a specified object, or creates a new record for the specified object.| |[sObject Get Deleted](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-getdeleted.md)|`/services/data/vXX.X/sobjects/sObject/deleted/​​​?start=startDateAndTime&end=endDateAndTime` Retrieves the list of individual records that have been deleted within the given timespan for the specified object.| |[sObject Describe](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-describe.md)|`/services/data/vXX.X/sobjects/sObject/describe` Completely describes the individual metadata at all levels for the specified object. For example, this can be used to retrieve the fields, URLs, and child relationships for the Account object.| |[sObject ApprovalLayouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-approvallayouts.md)|`/services/data/vXX.X/sobjects/sObject/describe/approvalLayouts`Retrieve a list of approval layouts for a specified object. This resource is available in REST API version 30.0 and later.| |[sObject CompactLayouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-compactlayouts.md)|`/services/data/vXX.X/sobjects/sObject/describe/compactLayouts` Retrieve a list of compact layouts for a specific object. This resource is available in REST API version 29.0 and later.| |[sObject Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-layouts.md)|`/services/data/vXX.X/sobjects/sObject/describe/layouts` `/services/data/vXX.X/sobjects/Global/describe/layouts`Retrieves lists of page layouts and their descriptions. You can request information for all of a specific object’s layouts or for layouts associated with a specified record type on a specific object.| |[sObject Named Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-named-layouts.md)|`/services/data/vXX.X/sobjects/sObject/describe/namedLayouts/layoutName` Retrieves information about alternate named layouts for a given object. This resource is available in REST API version 31.0 and later.| |[sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert.md)|`/services/data/vXX.X/sobjects/sObject/fieldName/fieldValue` Creates records or updates existing records (upserts records) based on the value of a specified external ID field.| |[List Views for an Object](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-listviews.md)|`/services/data/vXX.X/sobjects/sObject/listviews` `/services/data/vXX.X/sobjects/sObject/listviews/listViewId` Returns the list of list views for the specified sObject, including the ID and other basic information about each list view. You can also get basic information for a specific list view by ID.| |[List View Results](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-listviewresults.md)|`/services/data/vXX.X/sobjects/sObject/listviews/listViewID/results` Executes the SOQL query for the list view and returns the resulting data and presentation information.| |[List View Describe](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-listviewdescribe.md)|`/services/data/vXX.X/sobjects/sObject/listviews/queryLocator/describe` Returns detailed information about a list view, including the ID, the columns, and the SOQL query.| |[Recent List Views](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-recentlistviews.md)|`/services/data/vXX.X/sobjects/sObject/listviews/recent` Returns the list of recently used list views for the given object.| |[sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions.md)|`/services/data/vXX.X/sobjects/sObject/quickActions/` Access an object’s actions and the action details.| |[sObject Get Updated](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-getupdated.md)|`/services/data/vXX.X/sobjects/sObject/updated/​​​?start=startDateAndTime&end=endDateAndTime`| |[sObject Rows](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-retrieve.md)|`/services/data/vXX.X/sobjects/sObject/id` Accesses records based on a specified object and record ID. Retrieves, updates, or deletes records based on the HTTP method. Use the GET method to retrieve records or specific field values, the DELETE method to delete records, or the PATCH method to update records.| |[sObject Blob Get](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-blob-retrieve.md)|`/services/data/vXX.X/sobjects/sObject/id/blobField` Retrieves the specified blob field from an individual record and returns it as binary data.| |[sObject Relationships](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-relationships.md)|`/services/data/vXX.X/sobjects/sObject/id/relationshipName` Accesses records by traversing object relationships via friendly URLs. You can retrieve, update, or delete the record associated with the traversed relationship field. If there are multiple related records, you can retrieve the complete set of associated records.| |[sObject Rich Text Image Get](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-rich-text-image-retrieve.md)|`/services/data/vXX.X/sobjects/sObject/id/​richTextImageFields/fieldName/contentReferenceId` Gets the specified image data from a specific rich text area field in a given record.| |[Delete Lightning Experience Event Series](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-event-series-delete.md)|`/services/data/vXX.X/sobjects/Event/id/fromThisEventOnwards` Removes one or more IsRecurrence2 events in a series.| |Streaming Channel Push(Steaming API)|`/services/data/vXX.X/sobjects/StreamingChannel/channelId/push` Gets subscriber information, and pushes notifications for streaming channels. See the [Streaming API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/intro_stream.htm).| |[sObject User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-user-password.md)|`/services/data/vXX.X/sobjects/User/userId/password` Accesses user passwords based on the specified user ID. Sets, resets, or gets the expiration status of a user password based on the HTTP method. Use the GET method to retrieve a password’s expiration status, the POST method to set a password, or the DELETE method to initiate a password reset.| |[sObject Self-Service User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-self-service-user-password.md)|`/services/data/vXX.X/sobjects/SelfServiceUser/​selfServiceUserId/password`Accesses self-service user passwords based on the specified user ID. Sets, resets, or gets the expiration status of a self-service user password based on the HTTP method. Use the GET method to retrieve a password’s expiration status, the POST method to set a password, or the DELETE method to initiate a password reset.| |[Data Category Groups](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-knowledge-support-dcgroups.md)|`/services/data/vXX.X/support/dataCategoryGroups` Gets data category groups that are visible to the current user.| |[Data Category Detail](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-knowledge-support-dcdetail.md)|`/services/data/vXX.X/support/dataCategoryGroups/group/​dataCategories/​category` Gets data category details and the child categories by a given category.| |[Embedded Service Configuration Describe](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-embeddedserviceconfigdescribe.md)|`/services/data/vXX.X/support/embeddedservice/​configuration/​serviceName` Returns information corresponding to one or more service report templates in field service.| |Field Service Flow|`/services/data/vXX.X/support/fieldservice/Flow​?developerNames=flowName` Returns information corresponding to a field service flow.| |Field Service Report Template|`/services/data/vXX.X/support/fieldservice/​ServiceReportTemplate` Returns information corresponding to one or more service report templates in field service.| |[Articles Details](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-knowledge-support-artdetails.md)|`/services/data/vXX.X/support/knowledgeArticles/articleId` `/services/data/vXX.X/support/knowledgeArticles/articleUrlName` Gets all online article fields, accessible to the user.| |[Tabs](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-tabs.md)|`/services/data/vXX.X/tabs` Returns a list of all tabs—including Lightning page tabs—available to the current user, regardless of whether the user has chosen to hide tabs via the All Tabs (**+**) tab customization feature.| |[Themes](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-themes.md)|`/services/data/vXX.X/theme` Gets the list of icons and colors used by themes in the Salesforce application.| |Tooling API|`/services/data/vXX.X/tooling` Accesses features in the Tooling API. See the [Tooling API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/intro_api_tooling.htm).| |UI API|`/services/data/vXX.X/ui-api` Accesses features in the UI API. See the [User Interface API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_get_started.htm).| |Wave(Analytics REST API)|`/services/data/vXX.X/wave` Accesses features in the Analytics REST API. See the [Analytics REST API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.bi_dev_guide_rest.meta/bi_dev_guide_rest/bi_rest_overview.htm).| # Reference This section contains links to reference documentation. - **[Lightning Component Library](https://developer.salesforce.com/docs/platform/aura-platform/components/component-library.md)** The Lightning Component Library is your hub for component reference information, including the Component Reference with live examples, and tools for Lightning Web Security and Lightning Locker. - **[System Tag Reference](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-system-tags.md)** System tags represent framework definitions and are not available in the Component Library. - **[JavaScript API](https://developer.salesforce.com/docs/platform/aura-platform/ref-jsapi/ref-jsapi-intro.md)** The JavaScript API lists the publicly accessible methods for each object that you can use in JavaScript code, such as a controller or helper. The `$A` namespace is the entry point for using the framework in JavaScript code. # Reference The reference documentation for platform events covers an API object, Apex methods, limits, error codes, and standard platform events. Check out this object in the *Object Reference for the Salesforce Platform*. - [EventBusSubscriber](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_eventbussubscriber.htm) Check out these Apex resources in the *Apex Reference Guide*. - [EventBus Class](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_eventbus.htm) in the `System` namespace - [TriggerContext Class](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_eventbus_TriggerContext.htm) in the `EventBus` namespace Check out these resources about limits, error codes, and standard platform events. - **[Platform Event Allocations](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-event-limits.md)** Learn about the allocations available for platform event definitions, publishing and subscribing to platform events, and event delivery in Pub/Sub API clients, CometD clients, `empApi` Lightning components, and event relays. - **[Platform Event Error Status Codes](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-error-status-codes.md)** When publishing an event message results in an error, a status code is returned in the SaveResult. - **[Standard Platform Event Objects](https://developer.salesforce.com/docs/platform/platform-events/guide/objects/platform-events-standard-platform-event-objects.md)** Check out the standard platform events that Salesforce publishes. # Reference Apex Maps and Lists Visualforce pages that use dynamic bindings can reference the Apex `Map` and `List` data types in their markup. For example, if an Apex `List` is defined as: ```apex public List people { get { return new List{'Winston', 'Julia', 'Brien'}; } set; } public List iter { get { return new List{0, 1, 2}; } set; } ``` You can access the list values in a Visualforce page using `{!object}` syntax and array notation. ```apex
``` Similarly, if you have this Apex `Map`: ```visualforce public Map directors { get { return new Map { 'Kieslowski' => 'Poland', 'del Toro' => 'Mexico', 'Gondry' => 'France' }; } set; } ``` You can access the map’s keys and values in a Visualforce page using `{!object}` syntax and array notation. ```visualforce --
``` Use dynamic references to lists and maps in an `` tag to create forms using data that isn’t in your organization’s custom objects. Working with a single map can be much simpler than creating a series of instance variables in an Apex controller or creating a custom object just for the form data. Here’s a Visualforce page that uses a map to hold form data for processing by a custom controller. ```markup :
``` And here’s a simple controller that works with the form. ```controller public class ListsMapsController { public Map inputFields { get; set; } public ListsMapsController() { inputFields = new Map { 'firstName' => 'Jonny', 'lastName' => 'Appleseed', 'age' => '42' }; } public PageReference submitFieldData() { doSomethingInterestingWithInput(); return null; } public void doSomethingInterestingWithInput() { inputFields.put('age', (Integer.valueOf(inputFields.get('age')) + 10).format()); } } ``` A `Map` can contain references to sObjects or sObject fields. To update those items, reference a field name in the input field. ```apex public with sharing class MapAccCont { Map mapToAccount = new Map(); public MapAccCont() { Integer i = 0; for (Account a : [SELECT Id, Name FROM Account LIMIT 10]) { mapToAccount.put(i, a); i++; } } public Map getMapToAccount() { return mapToAccount; } } ``` ```visualforce ``` ## Unresolved Dynamic References Keep in mind the following issues that can arise at run time if a dynamic reference doesn’t resolve: - If there isn’t a value mapped to a particular key or the value is `null`, the Visualforce page returns an error message. For example, with this controller: ```apex public class ToolController { public Map toolMap { get; set; } public String myKey { get; set; } public ToolController() { Map toolMap = new Map(); toolMap.put('Stapler', 'Keeps things organized'); toolMap.put('Notebook', null); } } ``` This page causes an error at run time. ```visualforce ``` - If the key is `null`, the Visualforce page renders an empty string. For example, using the same controller as above, this page shows an empty space. ```visualforce ``` # Reference Flow Output Variable Values in a Wrapper Aura Component When you embed a flow in an Aura component, you can display or reference the flow’s variable values. Use the `onstatuschange` action to get values from the flow's output variables. Output variables are returned as an array. **note:** The variable must allow output access. If you reference a variable that doesn’t allow output access, attempts to get the variable are ignored. This example uses the JavaScript controller to pass the flow's accountName and numberOfEmployees variables into attributes on the component. Then, the component displays those values in output components. ```nolang

``` ```javascript ({ init: function (component) { // Find the component whose aura:id is "flowData" var flow = component.find("flowData"); // In that component, start your flow. Reference the flow's API Name. flow.startFlow("myFlow"); }, handleStatusChange: function (component, event) { if (event.getParam("status") === "FINISHED") { // Get the output variables and iterate over them var outputVariables = event.getParam("outputVariables"); var outputVar; for (var i = 0; i < outputVariables.length; i++) { outputVar = outputVariables[i]; // Pass the values to the component's attributes if (outputVar.name === "accountName") { component.set("v.accountName", outputVar.value); } else { component.set("v.numberOfEmployees", outputVar.value); } } } }, }); ``` **See Also** - [_Component Library_: lightning:flow Component](https://developer.salesforce.com/docs/component-library/bundle/lightning:flow/documentation) # Reference: PushTopic See [PushTopic](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_pushtopic.htm) in the *Object Reference for Salesforce and Lightning Platform*. # Reference: Streaming Channel Push REST API Gets subscriber information, and pushes notifications for streaming channels. ## Syntax **URI:** `/vXX.X/sobjects/StreamingChannel/Channel ID/push` **Available since release:** 29.0 **Formats:** JSON, XML **HTTP methods:** GET, POST **Authentication:** `Authorization: Bearer token` **Request body** For GET, no request body required. For POST, a request body that provides the push notification payload. This contains the following fields: |Name|Type|Description| |----|----|-----------| |`pushEvents`|array of push event payloads|List of event payloads to send notifications for.| Each push event payload contains the following fields: |Name|Type|Description| |----|----|-----------| |`payload`|string|Information sent with notification. Cannot exceed 3,000 single-byte characters.| |`userIds`|array of User IDs|List of subscribed users to send the notification to. If this array is empty, the notification will be broadcast to all subscribers on the channel.| **Request parameters:** None **Response data** For GET, information on the channel and subscribers is returned in the following fields: |Name|Type|Description| |----|----|-----------| |`OnlineUserIds`|array of User IDs|User IDs of currently subscribed users to this channel.| |`ChannelName`|string|Name of the channel, for example, `/u/notifications/ExampleUserChannel`.| For POST, information on the channel and payload notification results is returned in an array of push results, each of which contains the following fields: |Name|Type|Description| |----|----|-----------| |`fanoutCount`|number|The number of subscribers that the event got sent to. This is the count of subscribers specified in the POST request that were online. If the request was broadcast to all subscribers, fanoutCount will be –1. If no active subscribers were found for the channel, fanoutCount will be 0.| |`userOnlineStatus`|array of User online status information|List of User IDs the notification was sent to and their listener status. If `true` the User ID is actively subscribed and listening, otherwise `false`.| ## Example The following is an example JSON response of a GET request for `services/data/v29.0/sobjects/StreamingChannel/0M6D000000000g7KXA/push`: ```nolang { "OnlineUserIds" : [ "005D0000001QXi1IAG" ], "ChannelName" : "/u/notifications/ExampleUserChannel" } ``` Using a POST request to `services/data/v29.0/sobjects/StreamingChannel/0M6D000000000g7KXA/push` with a request JSON body of: ```nolang { "pushEvents": [ { "payload": "hello world!", "userIds": [ "005xx000001Svq3AAC", "005xx000001Svq4AAC" ] }, { "payload": "broadcast to everybody (empty user list)!", "userIds": [] } ] } ``` the JSON response data looks something like: ```nolang [ { "fanoutCount" : 1, "userOnlineStatus" : { "005xx000001Svq3AAC" : true, "005xx000001Svq4AAC" : false, } }, { "fanoutCount" : -1, "userOnlineStatus" : { } } ] ``` # Reference: StreamingChannel See [StreamingChannel](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_streamingchannel.htm) in the *Object Reference for Salesforce and Lightning Platform*. # Referencing a Static Resource in Visualforce Markup The way you reference a static resource in Visualforce markup depends on whether you want to reference a stand-alone file, or whether you want to reference a file that is contained in an archive (such as a .zip or .jar file): - To reference a standalone file, use `$Resource.` as a merge field, where _\_ is the name you specified when you uploaded the resource. For example: ```visualforce ``` or ```visualforce ``` - To reference a file in an archive, 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 ``` or ```visualforce ``` - You can use relative paths in files in static resource archives to refer to other content within the archive. For example, in your CSS file, named styles.css, you have the following style: ```html table { background-image: url('img/testimage.gif') } ``` When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create an archive (such as a zip file) that includes styles.css and img/testimage.gif. Make sure that the path structure is preserved in the archive. Then upload the archive file as a static resource named “style_resources”. Then, in your page, add the following component: ```visualforce ``` Since the static resource contains both the style sheet and the image, the relative path in the style sheet resolves and the image is displayed. - Through a custom controller, you can dynamically refer to the contents of a static resource using the `` tag. First, create the custom controller: ```apex global class MyController { public String getImageName() { return 'Picture.gif';//this is the name of the image } } ``` Then, refer to the `getImageName` method in your `` tag: ```visualforce ``` If the name of the image changes in the zip file, you can just change the returned value in `getImageName`. # Referencing an Existing Page with \ Use the `` tag when you want to duplicate the entire content of another page without making any changes. You can use this technique to reference existing markup that will be used the same way in several locations. **note:** You should not use `` if you are only duplicating components. [Custom components](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/comp-cust/pages-comp-cust.md) are better suited for reusable segments of code. For example, suppose you want to create a form that takes a user's name and displays it back to them. First, create a page called `formTemplate` that represents a reusable form and uses a controller called `templateExample`: ```visualforce ``` After you receive the prompt about `templateExample` not existing, use the following code to define that custom controller: ```apex public class templateExample{ String name; Boolean showGreeting = false; public PageReference save() { showGreeting = true; return null; } public void setNameField(String nameField) { name = nameField; } public String getNameField() { return name; } public Boolean getShowGreeting() { return showGreeting; } } ``` Next, return to `formTemplate` and add the following markup: ```visualforce ``` Note that nothing should happen if you click **Save**. This is expected behavior. Next, create a page called _displayName_, which includes `formTemplate`: ```visualforce ``` When you save this page, the entire `formTemplate` page is imported. When you enter a name and click **Save** the form passes a `true` value to the `showGreeting` field, which then renders the `` and displays the user's name. You can create another Visualforce page that uses `formTemplate` to display a different greeting. Create a page called `displayBoldName` and use the following markup: ```visualforce ``` Notice that although the displayed text changes, the `templateExample` logic remains the same. # Referencing the Canvas SDK The Canvas SDK is available on [GitHub](https://github.com/forcedotcom/salesforcecanvasframeworksdk), and you have two options for referencing it from your canvas app. - Host the SDK on your own Web server and access it there - Access the SDK hosted on the Salesforce server For example, here’s what the include statement looks like if you host the SDK on your own Web server: ```html ``` Here’s what the include statement looks like if you reference the hosted SDK: ```html ``` The ability to reference the SDK on the Salesforce server is useful when you want to include one of the SDK files in a Web app or from a Visualforce page. **See Also** - [Canvas SDK](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-framework-using-sdk.md) - [Authentication](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-authentication.md) # Referencing Untrusted Third-Party Content with iframes It’s a good idea to isolate static resources downloaded from an untrusted source. You can use an iframe to separate third-party content from your Visualforce page to provide an extra layer of security and help you protect your assets. To reference a static HTML file on a separate domain, use `$IFrameResource.` as a merge field, where _resource_name_ is the name you specified when you uploaded the resource. For example: ```nolang ``` The iframe tag injects JavaScript into both the parent document and the child iframe to establish a secure communication between the two elements. The parent document can have multiple iframes. Each uniquely named static resource lives in its own subdomain of `force-user-content.com`. Access to an iframe is not authenticated, so any third-party content it contains can’t access a user’s session ID. ## Communicating with the iframe in the Parent Document You can write JavaScript code in the parent document to communicate with the iframe. - To send a message to theiframe: ```nolang SfdcApp.iframe.sendMessage('theiframe', { key1: value1, key2: value2 }); ``` - To receive messages from theiframe: ```nolang SfdcApp.iframe.addMessageHandler('theiframe', function(data) { if(data.key1) { … } }); ``` - To catch an error from theiframe: ```nolang SfdcApp.iframe.addErrorHandler('theiframe', function(error) { console.log(error); }); ``` ## Communicating with the Parent Document in the iframe You can also communicate the other way from the iframe document. - To send a message to the parent document: ```nolang LCC.onlineSupport.sendMessage('containerUserMessage', { key1: value1, key2: value2 }); ``` - To set up a handler to receive messages from the parent document: ```nolang LCC.onlineSupport.addMessageHandler(function(message) { if(data.key1) { … } }); ``` To remove this handler: ```nolang LCC.onlineSupport.removeMessageHandler(function) ``` - To set up a handler for message errors from the parent document: ```nolang LCC.onlineSupport.addMessageErrorHandler(function(message) { if(data.key1) { … } }); ``` To remove this handler: ```nolang LCC.onlineSupport.removeMessageErrorHandler(function) ``` - To set up a handler for other types of errors: ```nolang LCC.onlineSupport.addErrorHandler(function(message) { if(data.key1) { … } }); ``` To remove this handler: ```nolang LCC.onlineSupport.removeErrorHandler(function) ``` # refresh Refreshes the current record page. ## Arguments None. # Refresh Metric Actions Update a metric's Current Value field if it's linked to a summary field in a Salesforce report. The refresh runs as the metric owner. This object is available in API version 34.0 and later. ## Supported REST HTTP Methods **URI:** Get a list of metric refresh actions: `/services/data/vXX.X/actions/standard/metricRefresh` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`metricId`|string|Required. The metric linked to a Salesforce report.| ## Outputs |Output|Type|Description| |------|----|-----------| |`resultingMessage`|string|The message that indicates the results of the metric refresh.| # Refresh Records Cached in Durable Store While Offline While it’s not possible to retrieve updated data from Salesforce while a client device is offline, it’s still possible to request updates when data is known to be stale. For example, after updating a record via imperative Apex, you would want any version of that record cached by LDS to be updated. It’s straightforward to write code that handles this process when your imperative Apex succeeds while online, but also handles an update error if the client device is offline. `getRecordNotifyChange()` is used to advertise the need to update cached records that were modified by imperative Apex. It isn’t supported at this time. Note that `getRecordNotifyChange(recordIds)` simply _notifies_ LDS that the records represented by `recordIds` provided in the function call are known to be stale. It doesn’t _share_ updated record values with LDS, even if those records are available offline. It’s the responsibility of LDS to retrieve the latest values for those records. LDS can only do so when the client is online. `refreshApex()` is used to request a refresh for data provisioned by an Apex `@wire`. It’s usable today and, while online, behaves as expected. However, while `refreshApex(valueProvisionedByApexWireService)` can be called while offline, it requires a network connection to actually succeed, and push a new value to the wired property or function. Using `getRecordNotifyChange()` and `refreshApex()` to request updates for cached data that are possibly stale is described in [Client-Side Caching of Apex Method Results](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_result_caching) in the _Lightning Web Components Developer Guide_. **See Also** - [_Lightning Web Components Developer Guide:_ Client-Side Caching of Apex Method Results](https://developer.salesforce.com/docs/platform/lwc/guide/apex-result-caching.html) - [_Lightning Web Components Developer Guide:_ `@salesforce/apex` in `@salesforce` Modules](https://developer.salesforce.com/docs/platform/lwc/guide/reference-salesforce-modules.html) # Refreshing Chart Data Using \ Update a Visualforce chart in response to a user’s actions by adding the `` component to Visualforce user interface elements that affect the chart’s data. The following markup displays a pie chart that can be updated by choosing a new year from a menu next to the chart: ```markup ``` This markup attaches a chart component to its data source by setting the chart’s `data` attribute to the Visualforce expression `{!pieData}`. The expression calls the `getPieData()` controller method, which returns the data. The chart is wrapped in an `` with an `id` attribute of `theChart`. An `` component is used to submit a new year back to the page’s controller when the chart needs to be updated. The `` tag displays the years available to chart, and a child `` tag submits the form whenever the menu changes. The `id` of the chart’s ``, `theChart`, is used in the `` `reRender` attribute to limit updating to the chart, instead of reloading the whole page. Finally, an `` component provides a status message while the chart is refreshing. It’s easy to replace the minimal text message with an animated graphic or text effect. ## `PieChartRemoteController` The controller for this page is an expansion of the pie chart controller used in [A Simple Charting Example](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-overview-simple-example.md). ```controller public class PieChartRemoteController { // The year to be charted public String chartYear { get { if (chartYear == Null) chartYear = '2013'; return chartYear; } set; } // Years available to be charted, for public static List getChartYearOptions() { List years = new List(); years.add(new SelectOption('2013','2013')); years.add(new SelectOption('2012','2012')); years.add(new SelectOption('2011','2011')); years.add(new SelectOption('2010','2010')); return years; } public List getPieData() { // Visualforce expressions can't pass parameters, so get from property return PieChartRemoteController.generatePieData(this.chartYear); } @RemoteAction public static List getRemotePieData(String year) { // Remoting calls can send parameters with the call return PieChartRemoteController.generatePieData(year); } // Private data "generator" private static List generatePieData(String year) { List data = new List(); if(year.equals('2013')) { // These numbers are absolute quantities, not percentages // The chart component will calculate the percentages 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)); } else { data.add(new PieWedgeData('Jan', 20)); data.add(new PieWedgeData('Feb', 35)); data.add(new PieWedgeData('Mar', 30)); data.add(new PieWedgeData('Apr', 40)); data.add(new PieWedgeData('May', 5)); data.add(new PieWedgeData('Jun', 10)); } 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 supports providing data to a Visualforce chart two different ways: - Using a Visualforce expression, `{!pieData}`, which calls the instance method `getPieData()`. - Using JavaScript remoting, by calling the `@RemoteAction` static method `getRemotePieData()` from a JavaScript method. **See Also** - [Refreshing Chart Data Using JavaScript Remoting](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-refreshing-data-javascript-remoting.md) - [Providing Chart Data via a Controller Method](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-overview-providing-data-controller-method.md) - [apex:actionSupport](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-actionsupport.md) - [apex:actionStatus](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-actionstatus.md) # Refreshing Chart Data Using JavaScript Remoting Update a Visualforce chart periodically, or in response to a user’s actions, using custom JavaScript. JavaScript code can respond to complex user activity or timer events, and use JavaScript remoting to retrieve new chart data whenever required. The following markup displays a pie chart that can be updated by choosing a new year from a menu next to the chart: ```visualforce
``` This markup attaches a chart component to its data source by setting the chart’s `data` attribute to the name of a JavaScript function, `retrieveChartData`, which returns the data. The name of the function is provided as a string. A static HTML `` menu’s `onChange` attribute calls a JavaScript function, `refreshRemoteChart()`, whenever the menu changes. There are two additional static HTML elements: two `` tags with IDs. The `` tags are empty when the page loads, and are updated via JavaScript to display status and error messages when necessary. The two JavaScript functions that precede the Visualforce markup are the glue between the Visualforce chart and the `@RemoteAction` controller method that provides the data. There are three links between the functions and the chart component: 1. The chart component’s `data` attribute is set to “retrieveChartData”, the name of the first JavaScript function. This tells the chart component to use the JavaScript function to load its data. The chart component invokes `retrieveChartData()` **directly** only once, when the chart is first created and the data is initially loaded. 2. Reloading happens when the second JavaScript function, `refreshRemoteChart()`, is called. This is the second link, from the `theYear` menu. When the year menu changes, `refreshRemoteChart()` is invoked, and it re-invokes the `retrieveChartData()` function to load a new set of data. 3. When `refreshRemoteChart()` invokes `retrieveChartData()`, it provides an anonymous function as a callback, which handles the result of the `@RemoteAction` call when it returns. This callback updates the chart by calling `RemotingPieChart.reload(data)`. The chart itself is `RemotingPieChart`, named by setting the `name` attribute, and `reload()` is a JavaScript function available on Visualforce charts once created, which accepts new data and then redraws the chart. This diagram illustrates these links between the different components of the page: ![Visualforce Charting and JavaScript Remoting](https://developer.salesforce.com/media/salesforce-pages-developers-guide/pages_charting_refreshing_data_javascript_remoting_sequence.png) The sequence for the initial loading of the chart is simple: the `` named `RemotePieChart` calls `retrieveChartData()` to get its initial data, and `retrieveChartData()` calls `RemotePieChart.show()` when it has the data. And, the chart appears. Updates are more complicated. When a new year is chosen from the `theYear` menu, the menu’s `onChange` event fires, which calls the `refreshRemoteChart()` function. `refreshRemoteChart()` in turn calls the `retrieveChartData()` function, and when the `@RemoteAction` returns new data, `retrieveChartData()` (via the callback provided by `refreshRemoteChart()`) calls `RemotePieChart.reload()`. And, the chart updates. Here are a couple of other items to note: - The `` uses the `hidden="true"` attribute to prevent the chart from displaying before there’s data to display. The `retrieveChartData()` function calls `RemotingPieChart.show()` to display the chart once the chart data is loaded. This and `RemotingPieChart.reload()` provide for much smoother chart animations than can be achieved using ``. - The `refreshRemoteData()` function sets the `statusElement` HTML `` to a “loading…” message before it attempts to update the data by calling `retrieveChartData()`, and then the anonymous callback function sets it to an empty string to hide the message once the data is returned and the chart updated. It’s a bit more work than using ``, for basically the same effect. You can easily show a “busy” animation or graphic using the same technique. ## `PieChartRemoteController` The controller for this page is an expansion of the pie chart controller used in [A Simple Charting Example](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-overview-simple-example.md). ```controller public class PieChartRemoteController { // The year to be charted public String chartYear { get { if (chartYear == Null) chartYear = '2013'; return chartYear; } set; } // Years available to be charted, for public static List getChartYearOptions() { List years = new List(); years.add(new SelectOption('2013','2013')); years.add(new SelectOption('2012','2012')); years.add(new SelectOption('2011','2011')); years.add(new SelectOption('2010','2010')); return years; } public List getPieData() { // Visualforce expressions can't pass parameters, so get from property return PieChartRemoteController.generatePieData(this.chartYear); } @RemoteAction public static List getRemotePieData(String year) { // Remoting calls can send parameters with the call return PieChartRemoteController.generatePieData(year); } // Private data "generator" private static List generatePieData(String year) { List data = new List(); if(year.equals('2013')) { // These numbers are absolute quantities, not percentages // The chart component will calculate the percentages 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)); } else { data.add(new PieWedgeData('Jan', 20)); data.add(new PieWedgeData('Feb', 35)); data.add(new PieWedgeData('Mar', 30)); data.add(new PieWedgeData('Apr', 40)); data.add(new PieWedgeData('May', 5)); data.add(new PieWedgeData('Jun', 10)); } 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 supports providing data to a Visualforce chart two different ways: - Using a Visualforce expression, `{!pieData}`, which calls the instance method `getPieData()`. - Using JavaScript remoting, by calling the `@RemoteAction` static method `getRemotePieData()` from a JavaScript method. **See Also** - [Refreshing Chart Data Using \](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-refreshing-data-actionsupport.md) - [Providing Chart Data Using a JavaScript Function](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-charting-overview-providing-data-javascript-function.md) - [JavaScript Remoting for Apex Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/javascript/pages-js-remoting.md) # Reject a Record Use the Process Approvals resource to reject a record or a collection of records. Each call takes an array of requests. The current user must be an assigned approver. ## Example usage ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/process/approvals/ -H "Authorization: Bearer token" -H "Content-Type: application/json" -d @reject.json" ``` ## Example request body reject.json file ```nolang { "requests" : [{ "actionType" : "Reject", "contextId" : "04iD0000000Cw6cIAC", "comments" : "This record is rejected."}] } ``` ## Example JSON response body ```nolang [ { "actorIds" : null, "entityId" : "001D000000I8mImIAJ", "errors" : null, "instanceId" : "04gD0000000CvmFIAS", "instanceStatus" : "Rejected", "newWorkitemIds" : [ ], "success" : true } ] ``` # Relationship Fields in a Header Row (2.0) Many objects in Salesforce are related to other objects. For example, Account is a parent of Contact. You can add a reference to a related object in a CSV file by representing the relationship in a column header. When you're processing records in the Bulk API, you use `RelationshipName.IndexedFieldName` syntax in a CSV column header to describe the relationship between an object and its parent, where RelationshipName is the relationship name of the field and IndexedFieldName is the indexed field name that uniquely identifies the parent record. Use the `describeSObjects()` call in the API to get the `relationshipName` property value for a field. Some objects also have relationships to themselves. For example, the `ReportsTo` field for a contact is a reference to another contact. If you're inserting a contact, you could use a `ReportsTo.Email` column header to indicate that you're using a contact's `Email` field to uniquely identify the `ReportsTo` field for a contact. The `ReportsTo` portion of the column header is the `relationshipName` property value for the `ReportsTo` field. The following CSV file uses a relationship: ```nolang FirstName,LastName,ReportsTo.Email Tom,Jones,buyer@salesforcesample.com ``` Note the following when referencing relationships in CSV header rows: - You can use a child-to-parent relationship, but you can't use a parent-to-child relationship. - You can use a child-to-parent relationship, but you can't extend it to use a child-to-parent-grandparent relationship. - You can only use indexed fields on the parent object. A custom field is indexed if its `External ID` field is selected. A standard field is indexed if its `idLookup` property is set to `true`. See the Field Properties column in the field table for each [standard object](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_list.htm). ## Relationship Fields for Custom Objects Custom objects use custom fields to track relationships between objects. Use the relationship name, which ends in `__r` (underscore-underscore-r), to represent a relationship between two custom objects. You can add a reference to a related object by representing the relationship in a column header. If the child object has a custom field with an `API Name` of `Mother_Of_Child__c` that points to a parent custom object and the parent object has a field with an `API Name` of `External_ID__c`, use the column header `Mother_Of_Child__r.External_ID__c` to indicate that you're using the parent object's `External ID` field to uniquely identify the `Mother Of Child` field. To use a relationship name in a column header, replace the `__c` in the child object's custom field with `__r`. For more information about relationships, see Understanding Relationship Names in the _Salesforce SOQL and SOSL Reference Guide_ at [www.salesforce.com/us/developer/docs/soql_sosl/index.htm](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/). The following CSV file uses a relationship: ```nolang Name,Mother_Of_Child__r.External_ID__c CustomObject1,123456 ``` ## Relationships for Polymorphic Fields A polymorphic field can refer to more than one type of object as a parent. For example, either a contact or a lead can be the parent of a task. In other words, the `WhoId` field of a task can contain the ID of either a contact or a lead. Because a polymorphic field is more flexible, the syntax for the column header has an extra element to define the type of the parent object. The syntax is: `ObjectType:RelationshipName.IndexedFieldName`. **important:** Starting with version 57.0 of the API, for `ObjectType` use apiName, which should include namespace, if any, and should include `__c` if the object is a custom object. The following sample includes two reference fields: 1. The `WhoId` field is polymorphic and has a `relationshipName` of `Who`. It refers to a lead and the indexed `Email` field uniquely identifies the parent record. 2. The `OwnerId` field is not polymorphic and has a `relationshipName` of `Owner`. It refers to a user and the indexed `Id` field uniquely identifies the parent record. ```nolang Subject,Priority,Status,Lead:Who.Email,Owner.Id Test Bulk API polymorphic reference field,Normal,Not Started,lead@salesforcesample.com,005D0000001AXYz ``` **warning:** The `ObjectType:` portion of a field column header is only required for a polymorphic field. You get an error if you omit this syntax for a polymorphic field. You also get an error if you include this syntax for a field that is not polymorphic. # Relationship Queries Client applications need to be able to query for more than a single type of object at a time. SOQL provides syntax to support these types of queries, called relationship queries, against standard objects and custom objects. Relationship queries traverse parent-to-child and child-to-parent relationships between objects to filter and return results. Relationship queries are similar to SQL joins. However, you cannot perform arbitrary SQL joins. The relationship queries in SOQL must traverse a valid relationship path as defined in the rest of this section. You can use relationship queries to return objects of one type based on criteria that applies to objects of another type, for example, “return all accounts created by Bob Jones and the contacts associated with those accounts.” There must be a parent-to-child or child-to-parent relationship connecting the objects. You can’t write arbitrary queries such as “return all accounts and users created by Bob Jones.” Use the following topics to understand and use relationship queries in SOQL. - [Understanding Relationship Names](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-understanding.md#understanding-relationship-names) - [Using Relationship Queries](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-using.md#using-relationship-queries) - [Understanding Relationship Names, Custom Objects, and Custom Fields](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-and-custom-objects.md#understanding-relationship-names-custom-objects-and-custom-fields) - [Understanding Query Results](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-results.md#understanding-query-results) - [null Values in Lookup Relationships and Outer Joins](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-lookup.md#null-values-in-lookup-relationships-and-outer-joins) - [Identifying Parent and Child Relationships](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-parent-child.md#identifying-parent-and-child-relationships) - [Understanding Relationship Fields and Polymorphic Fields](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-and-polymorph-keys.md#understanding-relationship-fields-and-polymorphic-fields) - [Understanding Relationship Query Limitations](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-limits.md#understanding-relationship-query-limitations) - [Using Relationship Queries with History Objects](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-hist.md#using-relationship-queries-with-history-objects) - [Using Relationship Queries with Data Category Selection Objects](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-datacat.md#using-relationship-queries-with-data-category-selection-objects) - [Using Relationship Queries with the Partner WSDL](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-query-partner-wsdl.md#using-relationship-queries-with-the-partner-wsdl) # Relaxed Tidying for the HTML5 Doctype To relax the default HTML tidying for HTML5 applications where it causes problems, set the `docType` to “html-5.0” and the API version to 28.0 or greater. Beginning in API version 28.0, the tidying behavior for Visualforce pages with `docType="html–5.0"` changed for the `POSTBACK` context, so that HTML5 tags and attributes aren’t stripped away. Visualforce always validates the XML correctness of every page when it’s saved, and requires that the page be well-formed XML, but post-process tidying no longer removes unknown tags or attributes for `POSTBACK` requests. This should make it much easier to work with HTML5 and JavaScript frameworks that use HTML attributes extensively. It’s worth remembering that while modern browsers are very good at doing their own tidying, that behavior is less consistent than rendering valid markup. Reduced HTML tidying in `html–5.0` mode represents a smaller safety net, in return for significantly increased flexibility. We recommend you use this relaxed tidying mode only on HTML5 pages that need it, and with HTML validation and debugging tools in hand. **note:** In API version 28.0 or greater, the scope of how the `docType` is determined for a page is different. When child pages are added to a root page using ``, if *any* page in the hierarchy is set to `docType="html–5.0"` and the *root* page is set to API version 28.0 or later, the *entire* page hierarchy is rendered in `html–5.0` mode. **See Also** - [Using a Custom Doctype](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-doctype.md) # remote Function Syntax and Parameters AJAX proxy uses `remoteFunction` to proxy calls. The `remoteFunction` syntax and parameters: ```javascript sforce.connection.remoteFunction({ url : endpoint_url, onSuccess : callback_method onFailure : error_callback method : http_method mimeType : "text/plain" | "text/xml" async : true | false requestHeaders : http_headers requestData : http_post_data cache : true | false timeout : client_side_timeout_in_ms }); ``` **note:** `cache` and `timeout` are available in version 10.0 and later. # Remote Methods and Inheritance You can call remote actions on your Apex controller that are inherited methods. When a `@RemoteAction` method is looked up or called, Visualforce inspects the page controller’s inheritance hierarchy and finds `@RemoteAction` methods in the controller’s ancestor classes. Here’s an example demonstrating this capability. The following Apex classes form a three-tier inheritance hierarchy: ```apex global with sharing class ChildRemoteController extends ParentRemoteController { } global virtual with sharing class ParentRemoteController extends GrandparentRemoteController { } global virtual with sharing class GrandparentRemoteController { @RemoteAction global static String sayHello(String helloTo) { return 'Hello ' + helloTo + ' from the Grandparent.'; } } ``` This Visualforce page simply calls the `sayHello` remote action. ```apex_page
[Results]
``` The remote method doesn’t exist in the `ChildRemoteController` class. Instead, it’s inherited from `GrandparentRemoteController`. # RemoteKeyCalloutEvent Notifies subscribers of callouts that fetch encrypted key material from a customer endpoint. This object is available in API versions 45.0 and later. The `RemoteKeyCalloutEvent` captures events related to the success or failure of a callout that fetches encrypted key material from an end point. Based on the Platform Events framework, a `RemoteKeyCalloutEvent` is published every time a callout is made to an external key service. This event lets you monitor your cache-only key callouts in real time, and receive alerts about any errors that might occur. You can subscribe to events with after insert Apex triggers and store events in custom objects, security information event management (SIEM), or other back-end systems. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows| | |Processes| | |Pub/Sub API| | |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/RemoteKeyCalloutEvent` ## Special Access Rules Access to `RemoteKeyCalloutEvent` data requires purchasing Salesforce Shield or Shield Platform Encryption. The `RemoteKeyCalloutEvent` only applies to callouts that fetch cache-only key material. ## Event Delivery Allocation Enforced Yes **See Also** - [*Apex Developer Guide*: Triggers](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm) - [*Apex Developer Guide*: Add an Apex Trigger](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_trigger.htm) - [*SOAP API Developer Guide*: Custom Objects](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_custom_objects.htm) - [*Salesforce Help:* Cache-Only Key Service](https://help.salesforce.com/articleView?id=security_pe_byok_cache.htm) ## Fields ### `Details` **Type:** textarea **Properties:** Nillable **Description:** A JSON representation with more information about the `StatusCode`. Not all status codes (for example, SUCCESS) show a populated Details field. Populated Details fields include key-value pairs that you can use to make Apex triggers and other programmatic assertions. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `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. ### `RequestIdentifier` **Type:** string **Properties:** Nillable **Description:** When Replay Detection for Cache-Only Keys is enabled, a unique marker automatically generated and sent with every callout. This marker includes the key identifier, a nonce generated for that callout instance, and the nonce required from the endpoint. ### `StatusCode` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** A code that characterizes the error. The full list of status codes is available in the WSDL file for your org. ### `TenantSecretID` **Type:** reference **Properties:** Nillable **Description:** The record ID of the tenant secret associated with the published event. ## Usage To view a `RemoteKeyCalloutEvent` and perform custom actions after your callout, create an after insert Apex trigger in Dev Console. These triggers let you assign custom actions for your event. You can set in-app alerts and send email alerts to people who maintain your key service, including users who don’t have a Salesforce login. For longer-term monitoring, you can store `RemoteKeyCalloutEvent` data in custom objects and custom fields, SIEM, or other back-end systems. Then use business rules to send alerts. For example, you can set an alert that sends admins an email when something is wrong with a key service. Here’s an example of an after insert trigger that stores `RemoteKeyCalloutEvent` results in a custom object called Key Service Callout Log. The custom object also draws data from the `TenantSecret` object. |Field Label|Field Name|Data Type| |-----------|----------|---------| |Key Service Callout Log ID|Name|Auto Number| |Details|Details__c|Text(255)| |Replay Detection|Replay_Detection__c|Text (255)| |Status Code|Status_Code__c|Text(255)| |Tenant Secret Id|Tenant_Secret_Id__c|Text(50)| |Tenant Secret Status|Tenant_Secret_Status__c|Text(255)| |Type|Type__c|Text(100)| |Version|Version__c|Number(10,0)| If you use this trigger sample, adjust the field API names to suit your needs. ```apex trigger RemoteKeyCalloutEvent on RemoteKeyCalloutEvent (after insert){ List l = new List(); Set TenantSecretIds = new Set(); Map TenantSecrets; for(RemoteKeyCalloutEvent event : Trigger.new){ if(event.TenantSecretId != null && !TenantSecretIds.contains(event.TenantSecretId)) TenantSecretIds.add(event.TenantSecretId); } if(TenantSecretIds != null && !TenantSecretIds.isEmpty()) TenantSecrets = new Map([SELECT Type, Version, Status FROM TenantSecret where Id In: TenantSecretIds]); for(RemoteKeyCalloutEvent event : Trigger.new){ Key_Service_Callout_Log__c log = new Key_Service_Callout_Log__c(); log.Status_Code__c = event.StatusCode; log.Tenant_Secret_ID__c = event.TenantSecretId; log.Replay_Detection__c = event.RequestIdentifier; log.Details__c = event.Details; if(TenantSecrets != null && TenantSecrets.containsKey(event.TenantSecretId)){ log.Type__c = TenantSecrets.get(event.TenantSecretId).Type; log.Version__c = TenantSecrets.get(event.TenantSecretId).Version; log.Tenant_Secret_Status__c = TenantSecrets.get(event.TenantSecretId).Status; } l.add(log); } insert l; } ``` Then, you can use this test case to verify that the trigger is working ```apex @IsTest public class without sharing TestRemoteKey { //important: do not enforce sharing @IsTest public static void myUnitMethod1(){ List eList = new List(); List tsList = [Select Id, Type, Status From TenantSecret]; for(TenantSecret ts : tsList){ RemoteKeyCalloutEvent e = new RemoteKeyCalloutEvent(); e.TenantSecretId = ts.Id; e.RequestIdentifier = '22222'+ts.Id; e.StatusCode = 'SUCCESS'; eList.add(e); } Test.startTest(); try { EventBus.publish(eList); Test.getEventBus().deliver(); System.debug('delivered... '); } catch(Exception ex) { System.debug(ex.getMessage()); Boolean expectedExceptionThrown = ex.getMessage().contains('New Event Cannot be Created') ? true : false; System.AssertEquals(expectedExceptionThrown, true); } ``` To troubleshoot callout errors, review the `StatusCode` and `Details` fields. These fields give you information about remote key callout errors or exceptions in raw JSON format. Successful, empty callout, and timeout responses return empty `Details` fields. # Remove a Custom Override Learn how to restore the default behavior of a standard button and tab. 1. From Setup, click **Object Manager**, and then click the object that you want to update. 2. Click **Buttons, Links, and Actions**, and then select **Edit** from the dropdown of the desired button or tab home page. 3. To remove the behavior in Salesforce Classic, select **No override (default behavior)**. To remove the behavior in Lightning Experience or the Salesforce mobile app, select **Use the Salesforce Classic override**. 4. Save your changes. **note:** When switching from Salesforce Classic to Lightning Experience, if the URL contains `nooverride=1` in Salesforce Classic, it changes to `nooverride=true` in Lightning Experience, and you don’t see overrides for the record you’re navigating to. **See Also** - [*Salesforce Help*: Custom Buttons and Links](https://help.salesforce.com/s/articleView?id=platform.customize_enterprise.htm&type=5) # removeClass() Removes a CSS class from a component. ## Signature `removeClass(Object element, String newClass)` ## Parameters **_element_:** Type: `Object`. The component to remove the class from. **_newClass_:** Type: `String`. The CSS class to be removed. ## Sample Code ```javascript //find a component with aura:id="myCmp" in markup var myCmp = component.find("myCmp"); $A.util.removeClass(myCmp, "myClass"); ``` # removeErrorHandler() Unmounts the error handling function. When using React, it’s necessary to unmount functions to remove them from the DOM and perform necessary cleanup. ## Sample Used within a JavaScript app uploaded as a static resource and referenced by `lightning:container`, this example unmounts 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 componentWillUnmount() { LCC.removeErrorHandler(this.onMessageError); } ``` ## Arguments | Name | Type | Description | | -------------------------------------- | -------- | -------------------------------------------------------------------------------- | | `handler: (errorMsg: string) => void)` | function | The function that handles error messages encountered in the messaging framework. | ## Response None. # removeEventHandler() Dynamically removes a component event handler for the specified event. ## Signature `removeEventHandler(String event, function handler, String phase)` ## Parameters **_event_:** Type: `String`. The name of the event to remove; for example, `'c:myEvent'`. **_handler_:** Type: `function`. A reference to the function or action to remove; for example., `'cmp.getReference("c.handleMyEvent");'`. **_phase_:** Type: `String`. Optional. The event bubbling phase for which to remove the handler. The default value is `"default"`. **See Also** - [addEventHandler()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-component-addeventhandler.md) # removeMessageHandler() Unmounts the message-handling function. When using React, it’s necessary to unmount functions to remove them from the DOM and perform necessary cleanup. ## Sample Used within a JavaScript app uploaded as a static resource and referenced by `lightning:container`, this example unmounts a message handling function. ```javascript componentWillUnmount() { LCC.removeMessageHandler(this.onMessage); } ``` ## Arguments | Name | Type | Description | | --------------------------------- | -------- | ---------------------------------------------------------------- | | `handler: (userMsg: any) => void` | function | The function that handles messages sent from the Aura component. | ## Response None. # Render a Visualforce Page as a PDF File You can generate a downloadable, printable PDF file of a Visualforce page using the PDF rendering service. Convert a page to PDF by changing the `` tag. ```visualforce ``` A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browser’s settings. Specific behavior depends on the browser, version, and user settings, and is outside the control of Visualforce. The following page includes some account details and renders as a PDF file. ```markup <-- Placeholder CSS file, supply your own, with your branding, etc. -->

Welcome to Universal Samples!

Thank you, , for becoming a new account with Universal Samples.

Your account details are:

Account Name
Account Rep
Customer Since
``` ![A Visualforce page rendered as a PDF](../../../../../media/salesforce-pages-developers-guide/pages_output_pdf_renderas_simple.png "A Visualforce Page Rendered as a PDF File") - **[Render a Visualforce Page as PDF from Apex](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-output-pdf-render-in-apex.md)** You can use the `PageReference.getContentAsPDF()` method in Apex to render a Visualforce page as PDF data. Then use Apex code to convert that PDF data to an email attachment, a document, a Chatter post, and so on. - **[Fonts Available When Using Visualforce PDF Rendering](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-output-pdf-supported-fonts.md)** Visualforce PDF rendering supports a limited set of fonts. To ensure that PDF output renders as you expect, use the supported font names. The default font is `serif`. - **[Visualforce PDF Rendering Considerations and Limitations](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-output-pdf-considerations.md)** Review these considerations and limitations when designing Visualforce pages intended to be rendered to PDF. Always verify the formatting and appearance of the PDF version of your page before you put it into production. - **[Component Behavior When Rendered as PDF](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-output-pdf-component-behavior.md)** Understanding how Visualforce components behave when converted to PDF is essential to creating pages that render well. **See Also** - [Using Custom Styles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-custom.md) - [Extending Salesforce Styles with Stylesheets](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-adding-stylesheets.md) # Render a Visualforce Page as PDF from Apex You can use the `PageReference.getContentAsPDF()` method in Apex to render a Visualforce page as PDF data. Then use Apex code to convert that PDF data to an email attachment, a document, a Chatter post, and so on. The following example is a simple three element form that selects an account and a report format, and then sends the resulting report to the specified email address. ```markup

Select a recently modified account to summarize.

``` This page is a simple user interface. When you’re generating a PDF file from Apex, all the action is in the Apex code. In this example, that code is in the `PdfEmailerController` class that’s specified as the page’s controller. ```controller public with sharing class PdfEmailerController { // Form fields public Id selectedAccount { get; set; } // Account selected on Visualforce page public String selectedReport { get; set; } // Report selected public String recipientEmail { get; set; } // Send to this email // Action method for the [Send Account Summary] button public PageReference sendReport() { // NOTE: Abbreviated error checking to keep the code sample short // You, of course, would never do this little error checking if(String.isBlank(this.selectedAccount) || String.isBlank(this.recipientEmail)) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Errors on the form. Please correct and resubmit.')); return null; // early out } // Get account name for email message strings Account account = [SELECT Name FROM Account WHERE Id = :this.selectedAccount LIMIT 1]; if(null == account) { // Got a bogus ID from the form submission ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid account. Please correct and resubmit.')); return null; // early out } // Create email Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); message.setToAddresses(new String[]{ this.recipientEmail }); message.setSubject('Account summary for ' + account.Name); message.setHtmlBody('Here\'s a summary for the ' + account.Name + ' account.'); // Create PDF PageReference reportPage = (PageReference)this.reportPagesIndex.get(this.selectedReport); reportPage.getParameters().put('id', this.selectedAccount); Blob reportPdf; try { reportPdf = reportPage.getContentAsPDF(); } catch (Exception e) { reportPdf = Blob.valueOf(e.getMessage()); } // Attach PDF to email and send Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment(); attachment.setContentType('application/pdf'); attachment.setFileName('AccountSummary-' + account.Name + '.pdf'); attachment.setInline(false); attachment.setBody(reportPdf); message.setFileAttachments(new Messaging.EmailFileAttachment[]{ attachment }); Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ message }); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email sent with PDF attachment to ' + this.recipientEmail)); return null; // Stay on same page, even on success } /***** Form Helpers *****/ // Ten recently-touched accounts, for the Account selection menu public List recentAccounts { get { if(null == recentAccounts){ recentAccounts = new List(); for(Account acct : [SELECT Id,Name,LastModifiedDate FROM Account ORDER BY LastModifiedDate DESC LIMIT 10]) { recentAccounts.add(new SelectOption(acct.Id, acct.Name)); } } return recentAccounts; } set; } // List of available reports, for the Summary Format selection menu public List reportFormats { get { if(null == reportFormats) { reportFormats = new List(); for(Map report : reports) { reportFormats.add(new SelectOption( (String)report.get('name'), (String)report.get('label'))); } } return reportFormats; } set; } /***** Private Helpers *****/ // List of report templates to make available // These are just Visualforce pages you might print to PDF private Map reportPagesIndex; private List> reports { get { if(null == reports) { reports = new List>(); // Add one report to the list of reports Map simpleReport = new Map(); simpleReport.put('name', 'simple'); simpleReport.put('label', 'Simple'); simpleReport.put('page', Page.ReportAccountSimple); reports.add(simpleReport); // Add your own, more complete list of PDF templates here // Index the page names for the reports this.reportPagesIndex = new Map(); for(Map report : reports) { this.reportPagesIndex.put( (String)report.get('name'), (PageReference)report.get('page')); } } return reports; } set; } } ``` This Apex controller can be conceptually divided into four parts. - The three public properties at the beginning capture the values submitted by the three input elements on the form. - The `sendReport()` action method fires when the Send Account Summary button is clicked. - The two public helper properties supply the values to use in the two select list input elements. - The private helpers at the end encapsulate the list of possible PDF report formats. You can add your own report by creating a Visualforce page and then adding an entry for it in this section. When the `sendReport()` action method fires, the code does the following. - It performs rudimentary error checking to ensure that the form fields have useful values. **note:** This error checking is inadequate for a form that must survive contact with real people. Perform more complete form validation in your production code. - Next it uses the value of the selected account to look up the name of that account. The account name is used in text that’s added to the email message. This lookup is also an opportunity to further validate the form value and ensure that a real account was selected. - It uses the `Messaging.SingleEmailMessage` class to assemble an email message, setting the To, Subject, and Body email message values. - The code creates a `PageReference` for the selected report format and then sets a page request parameter on it. The parameter is named “id”, and its value is set to the selected account’s ID. This `PageReference` represents a specific request to access this page in the context of the specified account. When `getContentAsPdf()` is called, the referenced Visualforce page has access to the specified account, and the page is rendered with that account’s details. - Finally, the PDF data is added to an attachment, and the attachment is added to the email message created earlier. The message is then sent. When using `PageReference.getContentAsPdf()`, the return type of the method call is `Blob`, which stands for “binary large object.” In Apex, the `Blob` data type represents untyped binary data. It’s only when the `reportPdf` variable is added to the `Messaging.EmailFileAttachment` with a content type of “application/pdf” that the binary data becomes a PDF file. In addition, the call to `getContentAsPdf()` is wrapped in a `try/catch` block. If the call fails, the `catch` replaces the hoped for PDF data with a `Blob` version of the exception’s message text. **note:** PDF generation can throw a variety of different exceptions. Not all of them can be caught. Your code should be prepared to manage uncatchable exceptions like `System.LimitException`. For details, see “Exceptions that Can’t be Caught” in [Exception Statements](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_exception_statements.htm) in the *Apex Developer Guide*. Rendering a Visualforce page as PDF data is treated semantically as a callout to an external service for various reasons. One reason is that the rendering service can fail in all the same ways that an external service can fail. For instance, the page references external resources that aren’t available. Another example is when the page contains too much data—usually in the form of images—or the rendering time exceeds a limit. For this reason, always wrap the `getContentAsPdf()` rendering call in a `try/catch` block when rendering a Visualforce page as PDF data in Apex. For completeness, here’s the report template page that’s rendered into PDF data by the Apex code. ```markup

Account Summary for {! Account.Name }

Phone
Fax
Website

``` **note:** Don’t use the `PageReference.getContent()` or `PageReference.getContentAsPDF()` methods to retrieve the output of a different Visualforce page with the same controller and controller extensions. Doing so can cause unexpected problems that are difficult to debug. Instead, pass the base URL of the destination page. ```apex new PageReference(Site.getBaseUrl() + '/apex/VisualforcePageName').getContentAsPdf(); ``` # Render Flows with Visualforce The standard user interface for running a flow can’t be customized by using Flow Builder. However, once you embed a flow in a Visualforce page, you can use Apex code and Visualforce markup to configure the flow at run time—such as to pass values between the Visualforce page and the flow or to customize the look and feel of the flow at run time. A flow is an application that collects, updates, edits, and creates Salesforce information. The following topics demonstrate how to embed and configure flows in a Visualforce page. - **[Embed Flows in Visualforce Pages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-adding.md)** To customize a flow’s look and feel or enhance its functionality, embed it in a Visualforce page. If your org has flows enabled for sites and portals, use the Visualforce page to deliver the flow to your Salesforce site, portal, or Experience Cloud site. - **[An Advanced Example of Using \](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-advanced.md)** The `` component is designed to make it easy to develop complex Visualforce interactions. You can access additional features in your flow by creating a custom controller. With custom controllers, you can build a page with multiple components that can interact with each other. Any flow within your organization can be individually referenced by its own Apex type, and the variables in the flow can be accessed as member variables. - **[Set Flow Variable Values from a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-setting-values.md)** After you embed your flow in a Visualforce page, set the initial values of variables, record variables, collection variables, and record collection variables through the `` component. - **[Get Flow Variable Values to a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-getting-values.md)** Flow variable values can be displayed in a Visualforce page. Once you’ve embedded your flow in a Visualforce page, you can use Visualforce markup to get values for variables or record variables. To display values for a collection variable or a record collection variable, you can use Visualforce markup to get the individual values contained in the collection. - **[Control Whether Users Can Pause a Flow from a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-pause.md)** After you embed a flow in a Visualforce page with the `` component, consider whether you want to let users pause flows from that page. Set the `allowShowPause` attribute to false to prevent users from pausing. - **[Customize How Users Resume Paused Flow Interviews](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-pausedid.md)** By default, users can resume their paused interviews from the Paused Interviews component on their home page. If you want to customize how and where users can resume their interviews, use the `pausedInterviewId` attribute on the `` component. - **[Configure the finishLocation Attribute in a Flow](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-finishlocation.md)** If `finishLocation` isn’t specified, users who click **Finish** start a new interview and see the first screen of the flow. You can shape what happens when a user clicks **Finish** on the final screen by using the `URLFOR` function, the `$Page` variable, or a controller. - **[Customize a Flow’s User Interface](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-customize-runtime-ui.md)** After you’ve embedded a flow in a Visualforce page, you can customize what the flow looks like at run time by applying custom styles using CSS. Using a combination of flow attributes and CSS classes, you can customize the individual parts of a flow, such as the button location, button style, background, and the look and feel of the screen labels. - **[Render Lightning Runtime for Flows in a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-flows-lightningruntime.md)** By default, when you embed a flow in a Visualforce page, the flow renders in Classic runtime. Like its name suggests, Classic runtime looks and feels like regular Visualforce pages and the Salesforce Classic desktop experience. To render a flow in Lightning runtime, add the `lightning:flow` Aura component to your Visualforce page. **See Also** - [*Salesforce Help*: Flow Builder](https://help.salesforce.com/articleView?id=flow.htm) # Render Lightning Runtime for Flows in a Visualforce Page By default, when you embed a flow in a Visualforce page, the flow renders in Classic runtime. Like its name suggests, Classic runtime looks and feels like regular Visualforce pages and the Salesforce Classic desktop experience. To render a flow in Lightning runtime, add the `lightning:flow` Aura component to your Visualforce page. **important:** Lightning Components for Visualforce is based on Lightning Out (Beta), a powerful and flexible feature you can use to embed Aura and Lightning web components into almost any web page. When used with Visualforce, some of the details become simpler. For example, you don’t need to deal with authentication, and you don’t need to configure a Connected App. In other ways, using Lightning Components for Visualforce is identical to using Lightning Out. See [Use Components Outside Salesforce with Lightning Out (Beta)](https://developer.salesforce.com/docs/platform/lwc/guide/lightning-out.html) in the *Lightning Web Components Developer Guide*. 1. Create a Lightning Out app that declares a dependency on the `lightning:flow` component. This app is globally accessible and extends `ltng:outApp`. Your Lightning Out app must exist in the same org as the Visualforce page. 2. To add the Lightning Components for Visualforce JavaScript library to your Visualforce page, use the `` component. 3. In the Visualforce page, reference the dependency app by using the syntax `$Lightning.use("theNamespace:theAppName”, function() {});` 4. Write a JavaScript function that creates the component on the page by using the syntax `$Lightning.createComponent(String type, Object attributes, String domLocator, function callback)`. ## Example Here’s an example of a Lightning app named `lightningOutApp`. ```html ``` To render a pre-existing flow called `myFlowName` in Lightning runtime, add `lightningOutApp` to the Visualforce page. The `$Lightning.createComponent()` function creates the component and inserts it into a `div` element called `flowContainer`. The component passes in initial values for the flow and handles a change in the flow interview status using the `onstatuschange` event handler. ```yaml
``` **See Also** - [*Lightning Aura Components Developer Guide*: Use Lightning Components in Visualforce Pages](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_visualforce.htm) - [*Lightning Aura Components Developer Guide*: Embed a Flow in a Custom Aura Component](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_using_flow_cmp.htm) - [*Component Library*: lightning:flow Component](https://developer.salesforce.com/docs/component-library/bundle/lightning:flow/documentation) # `renderEmailTemplate()` Replaces merge fields in text bodies of email templates with values from Salesforce records, even for polymorphic fields. The email template bodies and their corresponding `whoId` and `whatId` values are specified in the argument. ## Syntax ```nolang RenderEmailTemplateResult = connection.renderEmailTemplate(RenderEmailTemplateRequest[] renderRequests); ``` ## Usage The `renderEmailTemplate()` call is equivalent to rendering merge fields when sending an email with a custom template through the [sendEmail()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail.md) call. The `renderEmailTemplate()` call can take up to 10 RenderEmailTemplateRequest elements in its array argument, and each RenderEmailTemplateRequest can contain up to 10 template bodies. Each request is independent from the other requests in the array—an error in one request doesn’t affect the other requests. Similarly, an error in one template body doesn’t cause an error in other text bodies within the same request. The `renderEmailTemplate()` call substitutes a merge field with the value of either the `whatId` or `whoId` in RenderEmailTemplateRequest: The `whatId` and `whoId` field values of RenderEmailTemplateRequest are validated for each request. If the `whatId` doesn’t reference a valid what ID (a non-human object), or the `whoId` doesn’t reference a valid who ID (a human object), an error is set for the request. - If the merge field references a non-human object, it’s replaced with the corresponding value of `whatId`. For example, if a merge field references an account or opportunity, the `whatId` value is substituted. - If the merge field references a human object, it’s replaced with the corresponding value of `whoId`. For example, if a merge field references a contact, lead, or user, the `whoId` value is substituted. ## Sample Code—Java In this sample, the `renderEmailTemplate()` call substitutes all contact merge fields with the value from the specified _whoId_ argument. Similarly, the call substitutes the opportunity merge field (`{!Opportunity.Name}`) with the specified _whatId_ value. The second template body in this sample has an incorrect merge field (`{!Contact.SNARF}`), which causes an error on the second template. However, the entire template rendering request is successful. ```codesegment public void renderTemplates(String whoId, String whatId) throws ConnectionException, RemoteException, MalformedURLException { // Array of three template bodies. // The second template body generates an error. final String[] TEMPLATE_BODIES = new String[] { "This is a good template body {!Contact.Name}", "This is a bad template body {!Opportunity.Name} {!Contact.SNARF} ", "This is another good template body {!Contact.Name}"}; // Create request and add template bodies, whatId, and whoId. RenderEmailTemplateRequest req = new RenderEmailTemplateRequest(); req.setTemplateBodies(TEMPLATE_BODIES); req.setWhatId(whatId); req.setWhoId(whoId); // An array of results is returned, one for each request. // We only have one request. RenderEmailTemplateResult[] results = connection.renderEmailTemplate( new RenderEmailTemplateRequest[] { req }); if (results != null) { // Check results for our one and only request. // Check request was processed successfully, and if not, print the errors. if (!results[0].isSuccess()) { System.out.println( "The following errors were encountered while rendering email templates:"); for (Error err : results[0].getErrors()) { System.out.println(err.getMessage()); } } else { // Check results for each body template and print merged body RenderEmailTemplateBodyResult[] bodyResults = results[0].getBodyResults(); for( Integer i=0;i # RenderEmailTemplateResult Contains status and error information for a request processed by the `renderEmailTemplate()` call, including individual results of rendered email templates. |Name|Type|Description| |----|----|-----------| |`bodyResults`|[RenderEmailTemplateBodyResult](#renderemailtemplatebodyresult)[]|Contains status and error information for each template body that ``renderEmailTemplate()`` processed in a request, including merged body text of templates.| |`errors`|Error[]|Contains one or more errors that occurred when [renderEmailTemplate()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-renderemailtemplate.md#renderemailtemplate) rendered a request.| |`success`|boolean|Indicates whether a request was successfully processed (`true`) or not (`false`).| ## RenderEmailTemplateBodyResult Contains status and error information for each template body that ``renderEmailTemplate()`` processed in a request, including merged body text of templates. |Name|Type|Description| |----|----|-----------| |`errors`|[RenderEmailTemplateError](#renderemailtemplateerror)[]|Contains one or more errors that are associated with a template body that [renderEmailTemplate()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-renderemailtemplate.md#renderemailtemplate) processed.| |`mergedBody`|string|The text of the template body with the merge fields replaced with their corresponding values from Salesforce objects. The `whatId` and `whoId` fields on the request reference the Salesforce objects to use. The `mergedBody` field is populated only when the rendering of the template was successful (`success` is equal to `true`). If `success` is equal to `false`, `mergedBody` is null.| |`success`|boolean|Indicates whether a template body was successfully rendered (`true`) or not (`false`).| ## RenderEmailTemplateError An error that occurred when [renderEmailTemplate()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-renderemailtemplate.md#renderemailtemplate) processed a template body. |Name|Type|Description| |----|----|-----------| |`fieldName`|string[]|The merge field that affected the error condition.| |`message`|string|Error message text.| |`offset`|int|The offset in the template body text of the merge field that caused the error. The offset is calculated as the number of characters from the start of the body text. The offset is -1 if it can’t be determined because of insufficient contextual information.| |`statusCode`|[StatusCode](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode)|A code that characterizes the error. The full list of status codes is available in the WSDL file for your organization (see [Generating the WSDL File for Your Organization](https://developer.salesforce.com/docs/platform/api/quickstart/sforce-api-quickstart-steps-generate-wsdl.md)).| # Rendering Related Lists with Large Data Volumes **important:** Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain terms to avoid any effect on customer implementations. ## Situation The customer had hundreds of thousands of account records and 15 million invoices, which were within a custom object in a master-detail relationship with the account. Each account record took a long time to display because of the Invoices related list’s lengthy rendering time. ## Solution The delay in displaying the Invoices related list was related to data skew. While most account records had few invoice records, there were some records that had thousands of them. To reduce the delay, the customer tried to reduce the number of invoice records for those parents and keep data skew to a minimum in child objects. Using the `Enable Separate Loading of Related Lists` setting allowed the account detail to render while the customer was waiting for the related list query to complete. # Replace Design Tokens with Styling Hooks If you use design tokens to customize the styling of your Aura components, use SLDS global styling hooks instead. Custom components that use design tokens still work, but they no longer receive updates after LWC API version 61.0. By using styling hooks, you can cleanly adopt future product innovations and updated web accessibility standards. ## Replace Design Tokens with Styling Hooks Directly replace design tokens with `--slds` styling hooks in your Aura CSS file. ```nolang /* Aura Custom Component CSS */ .THIS .my-custom-container { background-color: var(--slds-g-color-surface-container-1); } ``` Most of the customization options provided by design tokens are available with SLDS global styling hooks. For a full list of global styling hooks, see the [Global Styling Hooks Reference](https://www.lightningdesignsystem.com/platforms/lightning/reference/). ## Styling if Styling Hooks are Unavailable Only Lightning Experience supports the latest global styling hooks. In containers such as Experience Cloud sites, newer styling hooks, such as the `--slds-g-color-*` styling hooks, aren’t available. To accommodate containers that can’t access these styling hooks, include an `--lwc` custom property as a fallback. Use this solution only if the component is expected to run in a container that doesn’t support styling hooks. Convert a design token to an `--lwc` property by adding `--lwc` as a prefix to the design token name. For example, instead of `t(colorTextBrand)`, use `var(--lwc-colorTextBrand)`. ## Example This example shows an Aura CSS file for a custom component that uses a design token to override the component’s background color. ```nolang /* Aura CSS using an Aura token to override*/ .THIS .my-custom-container { background-color: t(cardColorBackground); } ``` The best replacement is the new `--slds-g-color-*` styling hooks. However, in this case the container can’t access newer styling hooks. So this example replaces the design token by referencing a global color styling hook and also an `--lwc` property that’s derived from the original design token. ```nolang /* Aura Custom Component CSS */ .THIS .my-custom-container { background-color: var(--slds-g-color-surface-container-1, --lwc-cardColorBackground); } ``` **See Also** - [Salesforce Lightning Design System: Styling Hooks](https://www.lightningdesignsystem.com/platforms/lightning/styling-hooks/) # Replay Generic Streaming Events with Durable Generic Streaming A client can receive generic streaming events after it subscribes to a channel and as long as the Salesforce session is active. Events sent before a client subscribes to a channel or after a subscribed client disconnects from the Salesforce session are missed. However, a client can fetch the missed events within the 24-hour retention window by using Durable Generic Streaming. For more information about durable events, see [Message Durability](https://developer.salesforce.com/docs/platform/api-streaming/using/using-streaming-api-durability.md). ## Code Sample See theses code samples about replaying generic streaming events. - [Generic Streaming Quick Start](https://developer.salesforce.com/docs/platform/api-streaming/guide/generic-streaming-quick-start.md) # Replay PushTopic Streaming Events Salesforce stores PushTopic-based events for 24 hours and allows you to retrieve stored and new events. Subscribers can choose which events to receive by using replay options. For more information about durable events, see [Message Durability](https://developer.salesforce.com/docs/platform/api-streaming/guide/using-streaming-api-durability.md). ## Code Samples - [*GitHub*: Durable PushTopic Streaming Demo](https://github.com/developerforce/SalesforceDurablePushTopicDemo) - [*GitHub*: Streaming Replay Client Extensions](https://github.com/developerforce/StreamingReplayClientExtensions) # Replicating a Standard Case Feed Page The `support:CaseFeed` component includes all of the elements of the standard Case Feed page: - Email, Portal, Log a Call, and Case Note actions - Case activity feed - Feed filters - Highlights panel - Case following icon - Case followers list - Layout, print, and help links ## `support:CaseFeed` Attributes |Attribute Name|Attribute Type|Description|Required?|API Version|Access| |--------------|--------------|-----------|---------|-----------|------| |`caseId`|id|ID of the case record to display in Case Feed.|Yes|26.0|| |`id`|String|An identifier that allows the component to be referenced by other components in the page.| |26.0|global| |`rendered`|Boolean|A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.| |26.0|global| ## Use Case National Foods is a food service company supplying restaurants and corporate cafeterias throughout the United States. National’s support operations includes both call center agents who work primarily on desktop computers and field agents who work mainly on mobile devices. The company wanted a simplified Case Feed page that would be easy for its field agents to use, and also wanted to give its call center agents access to the full Case Feed functionality. National used the `support:CaseFeed` component to recreate the standard Case Feed page for its call center agents working on desktops, and created a custom page for its field agents working on mobile devices. ![Case Feed standard page](https://developer.salesforce.com/media/case-feed/case_feed_standard_page_example.png "Standard Case Feed page created with support:CaseFeed") ## Code Sample ```visualforce ``` The following sample shows an Apex class containing a controller extension to be used with the Visualforce page above. ```apex public class CasePageSelectorExtension { boolean isFieldAgent; String caseId; public CasePageSelectorExtension(ApexPages.StandardController controller) { List roles = [SELECT Id FROM UserRole WHERE Name = 'FieldAgent']; isFieldAgent = !roles.isEmpty() && UserInfo.getUserRoleId() == roles[0].Id; caseId = controller.getRecord().id; } public Component.Apex.OutputPanel getCasePage() { Component.Apex.OutputPanel panel = new Component.Apex.OutputPanel(); if (isFieldAgent) { Component.Apex.Detail detail = new Component.Apex.Detail(); detail.subject = caseId; panel.childComponents.add(detail); } else { Component.Support.CaseFeed caseFeed = new Component.Support.CaseFeed(); caseFeed.caseId = caseId; panel.childComponents.add(caseFeed); } return panel; } } ``` # Report on Deflections: The Deflection Signals Framework A `lightningcommunity:deflectionSignal` event is fired when a user initiates a case then views a deflection item that addresses their issue and causes them to abandon the case. For example, let’s say a user is filling out a form to create a customer case, and then sees a useful article on the page. After clicking the article, the user finds it helpful and decides that creating a case is unnecessary. A `lightningcommunity:deflectionSignal` event is then fired. The event includes information about the user’s interaction with the article. The user’s action is reported as a successful deflection because the user didn’t create a case. You can report on these events through custom report types with the target object Community Case Deflection Metrics. The signal appears in reports as either a Successful Deflection, Failed Deflection, or Potential Deflection. **note:** Only those `lightningcommunity:deflectionSignal` events that are triggered by authenticated users are reported. - **[Case Create Deflection Signal](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-case-create-deflection.md)** The `lightningcommunity:deflectionSignal` event is fired in an Aura site when a user is deflected away from creating a customer case. After a user views an article or discussion, they’re asked if the interaction was helpful, and whether they want to abandon their case. **See Also** - [Case Create Deflection Signal](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-case-create-deflection.md) # ReportAnomalyEvent Tracks anomalies in how users run or export reports, including unsaved reports. This object is available in API version 49.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers| | |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes| | |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/ReportAnomalyEvent` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. **note:** The Machine Learning (ML) models that power Threat Detection analyze data to ensure accurate identification, which requires a brief processing time. This results in an expected time difference between the Event Detection Date and the Event Creation Date. ## Event Delivery Allocation Enforced No ## Fields ### `EvaluationTime` **Type:** double **Properties:** Nillable **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Nillable **Description:** The time when the anomaly was reported. For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Nillable **Description:** The unique ID of the event, which is shared with the corresponding storage object. For example, `0a4779b0-0da1-4619-a373-0a36991dff90`. Use this field to correlate the event with its storage object. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `LoginKey` **Type:** string **Properties:** Nillable **Description:** The string that ties together all events in a given user's login session. The session starts with a login event and ends with either a logout event or the user session expiring. For example, lUqjLPQTWRdvRG4. ### `PolicyId` **Type:** reference **Properties:** Nillable **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. A relationship field. **Relationship Name:** Policy **Relationship Type:** Lookup **Refers To:** TransactionSecurityPolicy ### `PolicyOutcome` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** The result of the transaction policy. Possible values are: - `Error` - The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user isn't blocked from performing the operation. - `NoAction` - The policy didn't trigger. - `Notified` - A notification was sent to the recipient. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `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. ### `Report` **Type:** string **Properties:** Nillable **Description:** The report ID for the report for which this anomaly event was detected. For example, `00OD0000001leVCMAY`. If this anomaly resulted from a user executing an unsaved report, the value of this field is null. ### `Score` **Type:** double **Properties:** Nillable **Description:** A number from 0 through 1 that represents the anomaly score for the report execution or export tracked by this event. The anomaly score shows how the user's current report activity is different from their typical activity. A low score indicates that the user's current report activity is similar to their usual activity. A high score indicates that it's different. ### `SecurityEventData` **Type:** textarea **Properties:** Nillable **Description:** The set of features about the report activity that triggered this anomaly event. Let’s say, for example, that a user typically downloads 10 accounts but then they deviate from that pattern and download 1,000 accounts. This event is triggered and the contributing features are captured in this field. Potential features include row count, column count, average row size, the day of week, and the browser’s user agent used for the report activity. The data captured in this field also shows how much a particular feature contributed to this anomaly event being triggered, represented as a percentage. The data is in JSON format. **Example:** This example shows that the average row count contributed more than 95% to the anomaly being triggered. Other anomalous features, such as the autonomous system, day of the week the report was run, the browser used, and the number of columns, contributed much less. ```nolang [ { "featureName": "rowCount", "featureValue": "1937568", "featureContribution": “95.00 %" }, { "featureName": "autonomousSystem", "featureValue": "Bigleaf Networks, Inc.", "featureContribution": “1.62 %" }, { "featureName": "dayOfWeek", "featureValue": "Sunday", "featureContribution": “1.42 %" }, { "featureName": "userAgent", "featureValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36}", "featureContribution": “1.21 %" }, { "featureName": "periodOfDay", "featureValue": “Evening”, "featureContribution": “.09 %" }, { "featureName": "averageRowSize", "featureValue": "744", "featureContribution": “0.08 %" }, { "featureName": "screenResolution", "featureValue": "900x1440", "featureContribution": “0.07 %" } ] ``` ### `SessionKey` **Type:** string **Properties:** Nillable **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. For example, vMASKIU6AxEr+Op5. ### `SourceIp` **Type:** string **Properties:** Nillable **Description:** The source IP address of the client that logged in. For example, `126.7.4.2`. Session information contained in the fields SessionKey, LoginKey, SessionLevel, and SourceIp isn’t captured in any report resulting from an asynchronous operation. ### `Summary` **Type:** textarea **Properties:** Nillable **Description:** A text summary of the report anomaly that caused this event to be created. **Example:** - `Report was exported from an infrequent network (BigLeaf Networks Inc.)` - `Report was generated with an unusually high number of rows (111141)` ### `UserId` **Type:** reference **Properties:** Nillable **Description:** The origin user’s unique ID. For example, `005000000000123`. A polymorphic relationship field. **Relationship Name:** User **Relationship Type:** Lookup **Refers To:** User ### `Username` **Type:** string **Properties:** Nillable **Description:** The origin username in the format of `user@company.com` at the time the event was created. # ReportAnomalyEventStore Tracks anomalies in how users run or export reports, including unsaved reports. ReportAnomalyEventStore is an object that stores the event data of ReportAnomalyEvent. This object is available in API version 49.0 and later. ## Supported Calls `describeLayout()``describeSObjects()`, `getDeleted()`, `getUpdated()`, `query()` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. **note:** The Machine Learning (ML) models that power Threat Detection analyze data to ensure accurate identification, which requires a brief processing time. This results in an expected time difference between the Event Detection Date and the Event Creation Date. ## Fields ### `EvaluationTime` **Type:** double **Properties:** Filter, Nillable, Sort **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Filter, Sort **Description:** Required. The time when the anomaly was reported. For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Filter, Group, Sort **Description:** Required. The unique ID of the event. For example, `0a4779b0-0da1-4619-a373-0a36991dff90`. ### `LastReferencedDate` **Type:** dateTime **Properties:** Filter, Nillable, Sort **Description:** The timestamp for when the current user last viewed a record related to this record. ### `LastViewedDate` **Type:** dateTime **Properties:** Filter, Nillable, Sort **Description:** The timestamp for when the current user last viewed this record. If this value is null, it’s possible that this record was referenced (`LastReferencedDate`) and not viewed. ### `LoginKey` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The string that ties together all events in a given user's login session. The session starts with a login event and ends with either a logout event or the user session expiring. For example, lUqjLPQTWRdvRG4. ### `PolicyId` **Type:** reference **Properties:** Filter, Group, Nillable, Sort **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `PolicyOutcome` **Type:** picklist **Properties:** Filter, Group, Nillable, Restricted picklist, Sort **Description:** The result of the transaction policy. Possible values are: - `Error` - The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user isn't blocked from performing the operation. - `NoAction` - The policy didn't trigger. - `Notified` - A notification was sent to the recipient. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `Report` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The report ID for the report for which this anomaly event was detected. For example, `00OD0000001leVCMAY`. If this anomaly resulted from a user executing an unsaved report, the value of this field is null. ### `ReportAnomalyEventNumber` **Type:** string **Properties:** Autonumber, Defaulted on create, Filter, idLookup, Sort **Description:** The unique number automatically assigned to the event when it's created. You can't change the format or value for this field. ### `Score` **Type:** double **Properties:** Filter, Nillable, Sort **Description:** A number from 0 through 100 that represents the anomaly score for the report execution or export tracked by this event. The anomaly score shows how the user's current report activity is different from their typical activity. A low score indicates that the user's current report activity is similar to their usual activity, a high score indicates that it's different. ### `SecurityEventData` **Type:** textarea **Properties:** Nillable **Description:** The set of features about the report activity that triggered this anomaly event. Let’s say, for example, that a user typically downloads 10 accounts but then they deviate from that pattern and download 1,000 accounts. This event is triggered and the contributing features are captured in this field. Potential features include row count, column count, average row size, the day of week, and the browser’s user agent used for the report activity. The data captured in this field also shows how much a particular feature contributed to this anomaly event being triggered, represented as a percentage. The data is in JSON format. **Example:** This example shows that the average row count contributed more than 95% to the anomaly being triggered. Other anomalous attributes, such as the autonomous system, day of the week the report was run, the browser used, and the number of columns, contributed much less. ```nolang [ { "featureName": "rowCount", "featureValue": "1937568", "featureContribution": “95.00 %" }, { "featureName": "autonomousSystem", "featureValue": "Bigleaf Networks, Inc.", "featureContribution": “1.62 %" }, { "featureName": "dayOfWeek", "featureValue": "Sunday", "featureContribution": “1.42 %" }, { "featureName": "userAgent", "featureValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36}", "featureContribution": “1.21 %" }, { "featureName": "periodOfDay", "featureValue": “Evening”, "featureContribution": “.09 %" }, { "featureName": "averageRowSize", "featureValue": "744", "featureContribution": “0.08 %" }, { "featureName": "screenResolution", "featureValue": "900x1440", "featureContribution": “0.07 %" } ] ``` ### `SessionKey` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. For example, vMASKIU6AxEr+Op5. ### `SourceIp` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The source IP address of the client that logged in. For example, `126.7.4.2`. Session information contained in the fields SessionKey, LoginKey, SessionLevel, and SourceIp isn’t captured in any report resulting from an asynchronous operation. ### `Summary` **Type:** textarea **Properties:** Nillable **Description:** A text summary of the report anomaly that caused this event to be created. **Example:** - `Report was exported from an infrequent network (BigLeaf Networks Inc.)` - `Report was generated with an unusually high number of rows (111141)` ### `UserId` **Type:** reference **Properties:** Filter, Group, Nillable, Sort **Description:** The origin user’s unique ID. For example, `005000000000123`. ### `Username` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The origin username in the format of `user@company.com` at the time the event was created. ## Associated Object This object has the following associated object. It’s available in the same API version as this object. [ReportAnomalyEventStoreFeed](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_associated_objects_feed.htm): Feed tracking is available for the object. # reportError() 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. ## Signature `reportError (String message, Error error)` ## Parameters **_message_:** Type: `String`. The error message. **_error_:** Type: `Error`. An error object to be included in handling and reporting. # ReportEvent Tracks when reports are run in your org. You can use ReportEvent in a transaction security policy. ReportEvent is a big object that stores the event data of ReportEventStream. This object is available in API version 46.0 and later. ## Supported Calls `describeSObjects()`, `query()` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Salesforce Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. **See Also** - [*Big Objects Implementation Guide*](https://developer.salesforce.com/docs/atlas.en-us.bigobjects.meta/bigobjects/big_object.htm) ## Fields ### `ActionName` **Type:** string **Properties:** Nillable **Description:** The name of the action. ### `BotSessionIdentifier` **Type:** string **Properties:** Nillable **Description:** The bot session ID. ### `ColumnHeaders` **Type:** string **Properties:** Nillable **Description:** Comma-separated values of column headers of the report. Values listed are object names, field names, and field values except where aliases are used. For example, [Opportunity.Name, Opportunity.Type, Opportunity.Owner.UserRole.RollupDescription, Opportunity.Account.Name, Opportunity.Account.NumberOfEmployees, AGE]. ### `DashboardId` **Type:** reference **Properties:** Nillable **Description:** The ID of the dashboard that the report was part of. For example, 01ZB0000000PmoQ. This is a relationship field. **Relationship Name:** Dashboard **Relationship Type:** Lookup **Refers To:** Dashboard ### `DashboardName` **Type:** string **Properties:** Nillable **Description:** The title of the dashboard that the report was part of. ### `Description` **Type:** string **Properties:** Nillable **Description:** The description of the report. ### `DisplayedFieldEntities` **Type:** string **Properties:** Nillable **Description:** The API values of the fields that are displayed on the report, including the names of the entities of the grouped column fields. For example, `[ACCOUNTS, OWNERS]`. ### `EvaluationTime` **Type:** double **Properties:** Nillable **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Filter, Sort **Description:** The time when the specified report event was captured (after query execution takes place). For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Filter, Sort **Description:** The unique ID of the event. For example, 0a4779b0-0da1-4619-a373-0a36991dff90. ### `EventSource` **Type:** picklist **Properties:** Nillable, Restricted Picklist **Description:** The source of the event. Possible values are: - `API`—The user generated the report from an API call. - `Classic`—The user generated the report from the Salesforce Classic UI. - `Lightning`—The user generated the report from Lightning Experience. ### `ExecutionIdentifier` **Type:** string **Properties:** Nillable **Description:** When report data is divided into multiple report events, use this unique identifier to correlate the multiple data chunks. For example, if each chunk has the same `ExecutionIdentifier` of a50a4025-84f2-425d-8af9-2c780869f3b5,you can link them together to get all the data for the report execution. The `Sequence` field contains the incremental sequence numbers that indicate the order of the multiple events. ### `ExportFileFormat` **Type:** string **Properties:** Nillable **Description:** If the user exported the report, this value indicates the format of the exported report. Possible values are:Values are CSV or Excel. ### `Format` **Type:** picklist **Properties:** Defaulted on create, Nillable, Restricted picklist **Description:** The format of the report. Possible values are:Values are `Matrix`, `MultiBlock`, `Summary`, or `Tabular`. ### `GroupedColumnHeaders` **Type:** string **Properties:** Nillable **Description:** Comma-separated values of grouped column fields in summary, matrix, and joined reports. For example, `[USERNAME, ACCOUNT.NAME, TYPE, DUE_DATE, LAST_UPDATE, ADDRESS1_STATE]`. ### `IsScheduled` **Type:** boolean **Properties:** Defaulted on create **Description:** If TRUE, the report was scheduled. If FALSE, the report wasn’t scheduled. ### `LoginHistoryId` **Type:** reference **Properties:** Nillable **Description:** Tracks a user session so that you can correlate user activity with a particular series of report events. This field is also available on the LoginEvent, AuthSession, and LoginHistory objects, making it easier to trace events back to a user’s original authentication. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, 0YaB000002knVQLKA2. This is a relationship field. **Relationship Name:** LoginHistory **Relationship Type:** Lookup **Refers To:** LoginHistory ### `LoginKey` **Type:** string **Properties:** Nillable **Description:** The string that ties together all events in a given user's login session. The session starts with a login event and ends with either a logout event or the user session expiring. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, lUqjLPQTWRdvRG4. ### `Name` **Type:** string **Properties:** Nillable **Description:** The display name of the report. The value is null for report previews. ### `NumberOfColumns` **Type:** int **Properties:** Nillable **Description:** The number of columns in the report. ### `Operation` **Type:** picklist **Properties:** Nillable, Restricted Picklist **Description:** The context in which the report executed, such as from a UI (Classic, Lightning, Mobile), through an API (synchronous, asynchronous, Apex), or through a dashboard. Session information contained in the fields `SessionKey`, `LoginKey`, `SessionLevel`, and `SourceIp` isn’t captured in any report resulting from an asynchronous operation. Possible values are: - `ChartRenderedInEmbeddedAnalyticsApp`—Report executed from a rendered chart in an embedded Analytics app. - `ChartRenderedOnHomePage`—Report executed from a rendered chart on the home page. - `ChartRenderedOnVisualforcePage`—Report executed from a rendered chart on a VisualForce Page. - `DashboardComponentPreviewed`—Report executed from a Lightning dashboard component preview. - `DashboardComponentUpdated`—Report executed when a user refreshed a dashboard component. - `ProbeQuery`—Report executed from a probe query. - `ReportAddedToCampaign`—Report was added from an Add to Campaign action. - `ReportExported`—Report executed from a printable view or report export that wasn’t asynchronous nor an API export. - `ReportExportedAsynchronously`—Report was exported asynchronously. - `ReportExportedUsingExcelConnector`—Report was exported using the Excel connector. - `ReportOpenedFromMobileDashboard`—Report executed when a user clicked a dashboard component on a mobile device and drilled down to a report. - `ReportPreviewed`—Report executed when a user got preview results while using the report builder. - `ReportResultsAddedToEinsteinDiscovery`—Report executed synchronously from Einstein Discovery. - `ReportResultsAddedToWaveTrending`—Report executed when a user trended a report in CRM Analytics. - `ReportRunAndNotificationSent`—Report executed through the notifications API. - `ReportRunFromClassic`—Report executed from the Run Report option of Salesforce Classic. - `ReportRunFromLightning`—Report executed from the Run option in Lightning Experience from a non-mobile browser. - `ReportRunFromMobile`—Report executed from the Run Report option of the mobile Salesforce app. - `ReportRunFromReportingSnapshot`—Report executed through Snapshot Analytics. - `ReportRunFromRestApi`—Report executed from REST API. - `ReportRunFromSlackElevate`—Report executed from Slack Elevate. - `ReportRunUsingApexAsynchronousApi`—Report executed from the asynchronous Apex API. - `ReportRunUsingApexSynchronousApi`—Report executed from the synchronous Apex API. - `ReportRunUsingAsynchronousApi`—Report executed from an asynchronous API. - `ReportRunUsingSynchronousApi`—Report executed from a synchronous API. - `ReportScheduled`—Report was scheduled. - `Test`—Report execution resulted from a test. - `Unknown`—Report execution origin is unknown. ### `OwnerId` **Type:** reference **Properties:** Nillable **Description:** The ID of the folder, organization, or user who owns the report. If the report wasn’t saved, this value is the same as `UserId`. For example, 005B0000001vURv. This is a polymorphic relationship field. **Relationship Name:** Owner **Relationship Type:** Lookup **Refers To:** Folder, Organization, User ### `PolicyId` **Type:** reference **Properties:** Nillable **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. This is a relationship field. **Relationship Name:** Policy **Relationship Type:** Lookup **Refers To:** TransactionSecurityPolicy ### `PolicyOutcome` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** The result of the transaction policy. Possible values are: - `Block`—The user was blocked from performing the operation that triggered the policy. - `Error`—The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `FailedInvalidPassword`—The user entered an invalid password. - `FailedPasswordLockout`—The user entered an invalid password too many times. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user wasn’t blocked from performing the operation. - `NoAction`—The policy didn't trigger. - `Notified`—A notification was sent to the recipient. - `TwoFAAutomatedSuccess`—Salesforce Authenticator approved the request for access because the request came from a trusted location. After users enable location services in Salesforce Authenticator, they can designate trusted locations. When a user trusts a location for a particular activity, that activity is approved from the trusted location for as long as the location is trusted. Logging in from a recognized device is an example. - `TwoFADenied`—The user denied the approval request in the authenticator app, such as Salesforce Authenticator. - `TwoFAFailedGeneralError`—An error caused by something other than an invalid verification code, too many verification attempts, or authenticator app connectivity. - `TwoFAFailedInvalidCode`—The user provided an invalid verification code. - `TwoFAFailedTooManyAttempts`—The user attempted to verify identity too many times. For example, the user entered an invalid verification code repeatedly. - `TwoFAInitiated`—Salesforce initiated identity verification but hasn’t yet challenged the user. - `TwoFAInProgress`—Salesforce challenged the user to verify identity and is waiting for the user to respond or for Salesforce Authenticator to send an automated response. - `TwoFANoAction`—The policy specifies multi-factor authentication (formerly called two-factor authentication) as an action, but the user is already in a high-assurance session. - `TwoFARecoverableError`—Salesforce can’t reach the authenticator app to verify identity, but retries. - `TwoFAReportedDenied`—The user denied the approval request in the authenticator app, such as Salesforce Authenticator, and flagged the approval request to report to an administrator. - `TwoFASucceeded`—The user’s identity was verified. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `ProfileId` **Type:** reference **Properties:** Nillable **Description:** This is a relationship field. **Relationship Name:** Profile **Refers To:** Profile ### `QueriedEntities` **Type:** string **Properties:** Nillable **Description:** The entities in the SOQL query. For example, Opportunity, Lead, Account, or Case. Can also include custom objects. For relationship queries, the value of this field contains all entities involved in the query. If the query returns 0 records, then the value of this field is null. **Examples:** - For `SELECT Contact.FirstName, Contact.Account.Name from Contact`, the value of `QueriedEntities` is `Account, Contact`. - For `SELECT Account.Name, (SELECT Contact.FirstName, Contact.LastName FROM Account.Contacts) FROM Account`, the value of `QueriedEntities` is `Account, Contact`. - For `SELECT Id, Name, Account.Name FROM Contact WHERE Account.Industry = 'media'`, the value of `QueriedEntities` is `Account, Contact`. ### `Records` **Type:** json **Properties:** Nillable **Description:** A JSON string that represents the report’s data. For example, `{"totalSize":1,"rows":[{"datacells":["005B0000001vURv","001B000000fewai"]}]}`. ### `RelatedEventIdentifier` **Type:** string **Properties:** Nillable **Description:** Represents the `EventIdentifier` of the related event. For example, bd76f3e7-9ee5-4400-9e7f-54de57ecd79c. This field is populated only when the activity that this event monitors requires extra authentication, such as multi-factor authentication. In this case, Salesforce generates more events and sets the `RelatedEventIdentifier` field of the new events to the value of the `EventIdentifier` field of the original event. Use this field with the `EventIdentifier` field to correlate all the related events. If no extra authentication is required, this field is blank. ### `ReportId` **Type:** reference **Properties:** Nillable **Description:** The ID of the report associated with this event. For example, 00OB00000032FHdMAM. This is a relationship field. **Relationship Name:** Report **Relationship Type:** Lookup **Refers To:** Report ### `RoleId` **Type:** reference **Properties:** Nillable **Description:** This is a relationship field. **Relationship Name:** Role **Refers To:** UserRole ### `RowsProcessed` **Type:** double **Properties:** Nillable **Description:** The total number of rows returned in the report. When report data is divided into multiple report events, this value is the same for all data chunks. For more information, see `ExecutionIdentifier`. ### `Scope` **Type:** string **Properties:** Nillable **Description:** Defines the scope of the data on which the user ran the report. For example, users can run the report against all opportunities, opportunities they own, or opportunities their team owns. Possible values are: - `user`—User owns the objects the report was run against. - `team`—Team owns the objects the report was run against. - `organization`—Report was run against all applicable objects. ### `Sequence` **Type:** int **Properties:** Nillable **Description:** Incremental sequence number that indicates the order of multiple events that result from a given report execution. When a report execution returns many records, Salesforce splits this data into chunks based on the size of the records, and then creates separate multiple ReportEventStreams. The field values in each of these correlated ReportEventStreams are the same, except for `Records` and `Sequence`. `Records` contains the different data chunks. `Sequence` identifies each chunk in order. Every report execution has a unique `ExecutionIdentifier` value to differentiate it from other report executions. To view all the data chunks from a single report execution, use the `Sequence` and `ExecutionIdentifier` fields in combination. When a report executes, we provide the first 1,000 events with data in the `Records` field. Use the `ReportId` field to view the full report. ### `SessionKey` **Type:** string **Properties:** Nillable **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, vMASKIU6AxEr+Op5. ### `SessionLevel` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** Session-level security controls user access to features that support it, such as connected apps and reporting. Possible values are: - `HIGH_ASSURANCE`—A high assurance session was used for resource access. For example, when the user tries to access a resource such as a connected app, report, or dashboard that requires a high-assurance session level. - `LOW`—The user’s security level for the current session meets the lowest requirements. This low level isn’t available, nor used, in the Salesforce UI. User sessions through the UI are either standard or high assurance. You can set this level using the API, but users assigned this level experience unpredictable and reduced functionality in their Salesforce org. - `STANDARD`—The user’s security level for the current session meets the Standard requirements set in the org’s Session Security Levels. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. ### `SourceIp` **Type:** string **Properties:** Nillable **Description:** The source IP address of the client that logged in. For example, 126.7.4.2. ### `UserId` **Type:** reference **Properties:** Filter, Sort **Description:** The origin user’s unique ID. For example, `005B0000001vURv`. This is a polymorphic relationship field. **Relationship Name:** User **Relationship Type:** Lookup **Refers To:** User ### `Username` **Type:** string **Properties:** Nillable **Description:** The origin username in the format of `user@company.com` at the time the event was created. ## Standard SOQL Usage Currently, the only supported SOQL function on ReportEvent is `WHERE`, and you can only use comparison operators (`=`, `<`, `>`, `<=`, and `>=`) on the final expression in a `WHERE` clause. The `!=` operator isn’t supported. Date functions such as `convertTimezone()` aren’t supported. For example, `SELECT CALENDAR_YEAR(EventDate), Count(EventIdentifier) FROM ReportEvent GROUP BY CALENDAR_YEAR(EventDate)` returns an error. You can use date literals in your queries and some date and date/time functions like `TODAY`, `YESTERDAY`, and `LAST_n_DAYS:1`. However, these functions use comparison operators behind the scenes, so you can only use them in the final expression of a `WHERE` clause. ReportEvent allows filtering over three ordered fields: `UserId` (Beta), `EventDate`, and `EventIdentifier`. There’s a catch here: Your query doesn’t work unless you use the correct order and combination of these fields. Valid filters for ReportEvent queries are: - `UserId` alone - `EventDate` alone - `UserId` with `EventDate` - `EventDate` with `EventIdentifier` - `EventDate` can have a range filter when the order of the filter is `UserId`, `EventDate`. - `EventIdentifier` can have a range query when the order is `EventDate`, `EventIdentifier`. **note:** As a beta feature, the UserId filter in ReportEvent is a preview and isn’t part of the “Services” under your Main Services Agreement with Salesforce. Use this feature at your sole discretion, and make your purchase decisions only on the basis of generally available products and features. Salesforce doesn’t guarantee general availability of this feature within any particular time frame or at all, and we can discontinue it at any time. This feature is for evaluation purposes only, not for production use. It’s offered as is and isn’t supported, and Salesforce has no liability for any harm or damage arising out of or in connection with it. All restrictions, Salesforce reservation of rights, obligations concerning the Services, and terms for related Non-Salesforce Applications and Content apply equally to your use of this feature. This list provides some examples of valid and invalid queries. - **Unfiltered query** - **Valid**—Contains no `WHERE` clause, so no special rules apply. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent ``` - **Filter on `UserId`** (Beta) - **Valid**—You can filter solely on `UserId` (Beta). You can include a range query when you filter on `UserId` (Beta) alone. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE UserId='005B0000001vURv'<=TODAY ``` - **Valid**—Filter on `UserId` (Beta) and `EventDate`. EventDate can also have a range filter if the order of the filter is UserId (Beta), EventDate. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE UserId='005B0000001vURv' AND EventDate<=TODAY ``` - **Valid**— Filter on `UserId` (Beta), and sort the results. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE UserId = '005B0000001vURv' ORDER BY EventDate DESC ``` - **Invalid**—Filtering on `UserId` (Beta) and `EventIdentifier` field isn’t supported. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE UserId='005B0000001vURv' AND EventIdentifier='f0b28782-1ec2-424c-8d37-8f783e0a3754' ``` - **Filter on `EventDate`** - **Valid**—You can filter on `EventDate` using date literals. Or you can include a range query when you filter on `EventDate` alone. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE EventDate<=TODAY ``` - **Invalid**—Filtering on `EventDate` with standard date literals isn’t supported. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE EventDate=TODAY AND EventIdentifier='f0b28782-1ec2-424c-8d37-8f783e0a3754' ``` - **Invalid**—Filtering on `EventDate` with \<= or \>= operator and `EventIdentifier` field isn’t supported. ```soql SELECT DashboardId,Description,DisplayedFieldEntities,EventDate,Format,UserId FROM ReportEvent WHERE EventDate<=2014-11-27T14:54:16.000Z AND EventIdentifier='f0b28782-1ec2-424c-8d37-8f783e0a3754' ``` # ReportEventStream Tracks report-related actions, such as when a user runs or exports a report. This object is available in API version 46.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers| | |Flows| | |Processes| | |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/ReportEventStream` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Salesforce Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. ## Event Delivery Allocation Enforced No ## Fields ### `ActionName` **Type:** string **Properties:** Nillable **Description:** The name of the action. ### `BotId` **Type:** string **Properties:** Nillable **Description:** The ID of the bot. ### `BotSessionIdentifier` **Type:** string **Properties:** Nillable **Description:** The bot session ID. ### `ColumnHeaders` **Type:** string **Properties:** Nillable **Description:** Comma-separated values of column headers of the report. Values listed are object names, field names, and field values except where aliases are used. For example, [Opportunity.Name, Opportunity.Type, Opportunity.Owner.UserRole.RollupDescription, Opportunity.Account.Name, Opportunity.Account.NumberOfEmployees, AGE]. ### `DashboardId` **Type:** string **Properties:** Nillable **Description:** The ID of the dashboard that the report was part of. For example, 01ZB0000000PmoQ. ### `DashboardName` **Type:** string **Properties:** Nillable **Description:** The title of the dashboard that the report was part of. ### `Description` **Type:** string **Properties:** Nillable **Description:** The description of the report. ### `DisplayedFieldEntities` **Type:** string **Properties:** Nillable **Description:** The API values of the fields that are displayed on the report, including the names of the entities of the grouped column fields. For example, `[ACCOUNTS, OWNERS]`. ### `EvaluationTime` **Type:** double **Properties:** Nillable **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Nillable **Description:** The time when the specified report event was captured (after query execution takes place). For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Nillable **Description:** The unique ID of the event. For example, 0a4779b0-0da1-4619-a373-0a36991dff90. ### `EventSource` **Type:** picklist **Properties:** Nillable, Restricted Picklist **Description:** The source of the event. Possible values are: - `API`—The user generated the report from an API call. - `Classic`—The user generated the report from the Salesforce Classic UI. - `Lightning`—The user generated the report from Lightning Experience. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `ExecutionIdentifier` **Type:** string **Properties:** Nillable **Description:** When report data is divided into multiple report events, use this unique identifier to correlate the multiple data chunks. For example, if each chunk has the same `ExecutionIdentifier` of a50a4025-84f2-425d-8af9-2c780869f3b5, you can link them together to get all the data for the report execution. The `Sequence` field contains the incremental sequence numbers that indicate the order of the multiple events. ### `ExportFileFormat` **Type:** string **Properties:** Nillable **Description:** If the user exported the report, this value indicates the format of the exported report. Possible values are:Values are CSV or Excel. ### `Format` **Type:** picklist **Properties:** Defaulted on create, Nillable, Restricted picklist **Description:** The format of the report. Possible values are:Values are `Matrix`, `MultiBlock`, `Summary`, or `Tabular`. ### `GroupedColumnHeaders` **Type:** string **Properties:** Nillable **Description:** Comma-separated values of grouped column fields in summary, matrix, and joined reports. For example, `[USERNAME, ACCOUNT.NAME, TYPE, DUE_DATE, LAST_UPDATE, ADDRESS1_STATE]`. ### `IsScheduled` **Type:** boolean **Properties:** Defaulted on create **Description:** If TRUE, the report was scheduled. If FALSE, the report wasn’t scheduled. ### `LoginHistoryId` **Type:** reference **Properties:** Nillable **Description:** Tracks a user session so that you can correlate user activity with a particular series of report events. This field is also available on the LoginHistory, AuthSession, and LoginHistory objects, making it easier to trace events back to a user’s original authentication. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, 0YaB000002knVQLKA2. ### `LoginKey` **Type:** string **Properties:** Nillable **Description:** The string that ties together all events in a given user's login session. The session starts with a login event and ends with either a logout event or the user session expiring. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, lUqjLPQTWRdvRG4. ### `Name` **Type:** string **Properties:** Nillable **Description:** The display name of the report. The value is null for report previews. ### `NumberOfColumns` **Type:** int **Properties:** Nillable **Description:** The number of columns in the report. ### `Operation` **Type:** picklist **Properties:** Nillable, Restricted Picklist **Description:** The context in which the report executed, such as from a UI (Classic, Lightning, Mobile), through an API (synchronous, asynchronous, Apex), or through a dashboard. Possible values are: - `ChartRenderedInEmbeddedAnalyticsApp`—Report executed from a rendered chart in an embedded Analytics app. - `ChartRenderedOnHomePage`—Report executed from a rendered chart on the home page. - `ChartRenderedOnVisualforcePage`—Report executed from a rendered chart on a VisualForce Page. - `DashboardComponentPreviewed`—Report executed from a Lightning dashboard component preview. - `DashboardComponentUpdated`—Report executed when a user refreshed a dashboard component. Because the report resulted from an asynchronous operation, session information, contained in the fields `SessionKey`, `LoginKey`, `SessionLevel`, and `SourceIp`, isn’t captured. - `ProbeQuery`—Report executed from a probe query. - `ReportAddedToCampaign`—Report was added from an Add to Campaign action. - `ReportExported`—Report executed from a printable view or report export that wasn’t asynchronous nor an API export. - `ReportExportedAsynchronously`—Report was exported asynchronously. - `ReportExportedUsingExcelConnector`—Report was exported using the Excel connector. - `ReportOpenedFromMobileDashboard`—Report executed when a user clicked a dashboard component on a mobile device and drilled down to a report. - `ReportPreviewed`—Report executed when a user got preview results while using the report builder. - `ReportResultsAddedToEinsteinDiscovery`—Report executed synchronously from Einstein Discovery. - `ReportResultsAddedToWaveTrending`—Report executed when a user trended a report in Einstein Analytics. - `ReportRunAndNotificationSent`—Report executed through the notifications API. - `ReportRunFromClassic`—Report executed from the Run Report option of Salesforce Classic. - `ReportRunFromLightning`—Report executed from the Run option in Lightning Experience from a non-mobile browser. - `ReportRunFromMobile`—Report executed from the Run Report option of the mobile Salesforce app. - `ReportRunFromReportingSnapshot`—Report executed through Snapshot Analytics. - `ReportRunFromRestApi`—Report executed from REST API. - `ReportRunFromSlackElevate`—Report executed from Slack Elevate. - `ReportRunUsingApexAsynchronousApi`—Report executed from the asynchronous Apex API. - `ReportRunUsingApexSynchronousApi`—Report executed from the synchronous Apex API. - `ReportRunUsingAsynchronousApi`—Report executed from an asynchronous API. - `ReportRunUsingSynchronousApi`—Report executed from a synchronous API. - `ReportScheduled`—Report was scheduled. - `Test`—Report execution resulted from a test. - `Unknown`—Report execution origin is unknown. ### `OwnerId` **Type:** string **Properties:** Nillable **Description:** The ID of the folder, organization, or user who owns the report. This value is blank if the report wasn’t saved. For example, 005B0000001vURvIAM. ### `PlannerId` **Type:** string **Properties:** Nillable **Description:** The ID of the agent planner. ### `PolicyId` **Type:** reference **Properties:** Nillable **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `PolicyOutcome` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** The result of the transaction policy. Possible values are: - `Block`—The user was blocked from performing the operation that triggered the policy. - `Error`—The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `FailedInvalidPassword`—The user entered an invalid password. - `FailedPasswordLockout`—The user entered an invalid password too many times. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user wasn't blocked from performing the operation. - `NoAction`—The policy didn't trigger. - `Notified`—A notification was sent to the recipient. - `TwoFAAutomatedSuccess`—Salesforce Authenticator approved the request for access because the request came from a trusted location. After users enable location services in Salesforce Authenticator, they can designate trusted locations. When a user trusts a location for a particular activity, such as logging in from a recognized device, that activity is approved from the trusted location for as long as the location is trusted. - `TwoFADenied`—The user denied the approval request in the authenticator app, such as Salesforce Authenticator. - `TwoFAFailedGeneralError`—An error caused by something other than an invalid verification code, too many verification attempts, or authenticator app connectivity. - `TwoFAFailedInvalidCode`—The user provided an invalid verification code. - `TwoFAFailedTooManyAttempts`—The user attempted to verify identity too many times. For example, the user entered an invalid verification code repeatedly. - `TwoFAInitiated`—Salesforce initiated identity verification but hasn’t yet challenged the user. - `TwoFAInProgress`—Salesforce challenged the user to verify identity and is waiting for the user to respond or for Salesforce Authenticator to send an automated response. - `TwoFANoAction`—The policy specifies multi-factor authentication (formerly called two-factor authentication) as an action, but the user is already in a high-assurance session. - `TwoFARecoverableError`—Salesforce can’t reach the authenticator app to verify identity, but will retry. - `TwoFAReportedDenied`—The user denied the approval request in the authenticator app, such as Salesforce Authenticator, and also flagged the approval request to report to an administrator. - `TwoFASucceeded`—The user’s identity was verified. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `ProfileId` **Type:** reference **Properties:** Nillable **Description:** This is a relationship field. **Relationship Name:** Profile **Refers To:** Profile ### `QueriedEntities` **Type:** string **Properties:** Nillable **Description:** The entities in the SOQL query. For example, Opportunity, Lead, Account, or Case. Can also include custom objects. For relationship queries, the value of this field contains all entities involved in the query. If the query returns 0 records, then the value of this field is null. **Examples:** - For `SELECT Contact.FirstName, Contact.Account.Name from Contact`, the value of `QueriedEntities` is `Account, Contact`. - For `SELECT Account.Name, (SELECT Contact.FirstName, Contact.LastName FROM Account.Contacts) FROM Account`, the value of `QueriedEntities` is `Account, Contact`. - For `SELECT Id, Name, Account.Name FROM Contact WHERE Account.Industry = 'media'`, the value of `QueriedEntities` is `Account, Contact`. ### `Records` **Type:** json **Properties:** Nillable **Description:** A JSON string that represents the report’s data. For example, `{"totalSize":1,"rows":[{"datacells":["005B0000001vURv","001B000000fewai"]}]}`. ### `RelatedEventIdentifier` **Type:** string **Properties:** Nillable **Description:** Represents the `EventIdentifier` of the related event. For example, bd76f3e7-9ee5-4400-9e7f-54de57ecd79c. This field is populated only when the activity that this event monitors requires extra authentication, such as multi-factor authentication. In this case, Salesforce generates more events and sets the `RelatedEventIdentifier` field of the new events to the value of the `EventIdentifier` field of the original event. Use this field with the `EventIdentifier` field to correlate all the related events. If no extra authentication is required, this field is blank. ### `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. ### `ReportId` **Type:** string **Properties:** Nillable **Description:** The ID of the report associated with this event. For example, 00OB00000032FHdMAM. ### `RoleId` **Type:** reference **Properties:** Nillable **Description:** This is a relationship field. **Relationship Name:** Role **Refers To:** UserRole ### `RowsProcessed` **Type:** double **Properties:** Nillable **Description:** The total number of rows returned in the report. When report data is divided into multiple report events, this value is the same for all data chunks. For more information, see `ExecutionIdentifier`. ### `Scope` **Type:** string **Properties:** Nillable **Description:** Defines the scope of the data on which the user ran the report. For example, users can run the report against all opportunities, opportunities they own, or opportunities their team owns. Possible values are: - `user`—User owns the objects the report was run against. - `team`—Team owns the objects the report was run against. - `organization`—Report was run against all applicable objects. ### `Sequence` **Type:** int **Properties:** Nillable **Description:** Incremental sequence number that indicates the order of multiple events that result from a given report execution. When a report execution returns many records, Salesforce splits this data into chunks based on the size of the records, and then creates multiple correlated ReportEventStreams. The field values in each of these correlated ReportEventStreams are the same, except for `Records`, which contains the different data chunks, and `Sequence`, which identifies each chunk in order. Every report execution has a unique `ExecutionIdentifier` value to differentiate it from other report executions. To view all the data chunks from a single report execution, use the `Sequence` and `ExecutionIdentifier` fields in combination. When a report executes, we provide the first 1,000 events with data in the `Records` field. Use the `ReportId` field to view the full report. ### `SessionKey` **Type:** string **Properties:** Nillable **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. For example, vMASKIU6AxEr+Op5. ### `SessionLevel` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** Session-level security controls user access to features that support it, such as connected apps and reporting. Possible values are: - `HIGH_ASSURANCE`—A high assurance session was used for resource access. For example, when the user tries to access a resource such as a connected app, report, or dashboard that requires a high-assurance session level. - `LOW`—The user’s security level for the current session meets the lowest requirements. This low level isn’t available, nor used, in the Salesforce UI. User sessions through the UI are either standard or high assurance. You can set this level using the API, but users assigned this level experience unpredictable and reduced functionality in their Salesforce org. - `STANDARD`—The user’s security level for the current session meets the Standard requirements set in the org’s Session Security Levels. This value is null if the event that was generated was from a dashboard refresh, a multi-block report, or a scheduled report. ### `SourceIp` **Type:** string **Properties:** Nillable **Description:** The source IP address of the client that logged in. For example, 126.7.4.2. ### `UserId` **Type:** reference **Properties:** Nillable **Description:** The origin user’s unique ID. For example, `005000000000123`. ### `Username` **Type:** string **Properties:** Nillable **Description:** The origin username in the format of `user@company.com` at the time the event was created. # Reporting |Goal|Best Practice| |----|-------------| |Maximizing reporting performance by:
  • Partitioning data to match its likely use
  • Minimizing the number of records per object
|Reduce the number of records to query—use a value in the data to segment the query. For example, query for only a single state instead of for all states. (See [Divisions](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-infrastructure-divisions.md).)| |Reducing the number of joins|
  • Minimize the number of:
    • Objects queried in the report
    • Relationships used to generate the report
  • De-normalize data when practical—“over de-normalizing” the data results in more overhead. Use summarized data stored on the parent record for the report. This practice is more efficient than having the report summarize the child records.
    | |Reducing the amount of data returned|Reduce the number of fields queried—only add fields to a report, list view, or SOQL query that is required.| |Reducing the number of records to query|
    • Reduce the amount of data by archiving unused records—move unused records to a custom object table to reduce the size of the report object.
    • Use report filters that emphasize the use of standard or custom indexed fields. Use index fields in report filters, whenever possible.
    | # Request an App Review on a Mobile Device A Lightning web component can use a mobile device to prompt users to rate and submit a review of your app to the app stores (Apple and Google). Their feedback can help improve your app experience, encourage downloads, and improve your app’s discoverability. AppReviewService requires access to platform-specific APIs that are available only within compatible Salesforce mobile apps. **important:** AppReviewService does not and cannot function when running in a web browser, whether on a desktop or mobile device. - **[AppReviewService User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-appreviewservice-intro.md)** Your component can deliver any user experience you desire. - **[Use the AppReviewService API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-appreviewservice-in-a-lightning-component.md)** To develop a Lightning web component with app review features, use the AppReviewService API. - **[AppReviewService Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-appreviewservice-example.md)** Here’s a minimal but complete example of a Lightning web component that uses AppReviewService to request an app review. - **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-appreviewservice-compatibility.md)** AppReviewService 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 AppReviewService 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-appreviewservice-considerations.md)** Consider these guidelines and limitations when developing features that use the AppReviewService API. **See Also** - [_Lightning Web Components Developer Guide:_ AppReviewService API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-appreviewservice.html) # Request Bodies To perform a POST, PATCH, or PUT request, create a request body formatted in either XML or JSON. This chapter lists the request bodies. - **[Work Type](https://developer.salesforce.com/docs/platform/api-rest/guide/request-body-ls-worktype.md)** Details about the type of work to be performed. - **[Skill Requirement](https://developer.salesforce.com/docs/platform/api-rest/guide/request-body-ls-skillrequirement.md)** List of skills that are required to complete a particular task for a work type. # Request: URL Template Parameters All URL template parameters are URL-encoded and sent via an HTTPS GET method. This list includes all template parameters used by the Salesforce federated search connector. ## OpenSearch Namespace | Parameter | Description | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `{searchTerms}` | Replaced by the search query terms that the user entered in the Salesforce search field. A SOSL clause isn’t supported. | | `{count}` | The number of search results per page desired by the search client. | | `{startIndex}` | By default, the index of the first result is 1, unless defined otherwise by the indexOffset attribute of the `` element. | | `{inputEncoding}` | If present in the template, this parameter is always set to UTF-8. | | `{outputEncoding}` | If present in the template, this parameter is always set to UTF-8. | ## Salesforce Federated Search Namespace | Parameter | Description | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `{sfdc:userId}` | The unique ID of the user who triggered the search. Because OAuth authentication is done with the same bearer token for all users, it authorizes, but doesn’t identify, the user. This parameter gives the identity of the user. The external search provider doesn’t send `userId` if the connection to the external data source is anonymous and not authenticated with OAuth. | | `{sfdc:userLogin}` | The login name of the user who triggered the search. The external search provider doesn’t send `userLogin` if the connection to the external data source is anonymous and not authenticated with OAuth. | | `{sfdc:userEmail}` | The email address of the user who triggered the search. The external search provider doesn’t send `userEmail` if the connection to the external data source is anonymous and not authenticated with OAuth. | | `{sfdc:orgId}` | The org ID of the user who triggered the search. | | `{sfdc:searchSyntax}` | Declares the syntax of the `{searchTerms}` parameter. Its value is always SOSL (uppercase). The search provider can use the parameter to determine precisely which syntax parser to use. | | `{sfdc:searchById}` | When the value of this boolean parameter is `true`, it restricts the search to a single record by its ID. The `{searchTerms}` must be set to the record ID. This parameter is used by the federated search connector to retrieve specific record data. If the OpenSearch description supports this parameter, the federated search connector sets this parameter to `true` and the search is restricted to the single record corresponding to the ID specified in `{searchTerms}`. If the OpenSearch description doesn’t support this parameter, the federated search connector searches the first few terms of the record titles. From the results, the connector selects only the record with the expected ID. This type of search is referred to as a fallback search, and can be less accurate than searching directly on the record ID. | | `{sfdc:recordType}` | Restricts the scope of the search request to a specific record type. Its value is the name of a declared ``. The supported record types are declared with the `` element. | | `{sfdc:sortField}` | Defines the name of the field by which search results are sorted. If it’s sortable, the field can be one of the common fields of the Atom format (title, id, link, summary, content, updated, published). Otherwise, set a declared sortable custom field by using ``. By default, this parameter isn’t present, and the search results are sorted by relevance. The API intentionally doesn’t follow the OpenSearch Community extension SRU because the Salesforce implementation is limited to sorting on a single field, without a sort schema. | | `{sfdc:sortDirection}` | Defines the sort direction with a value of either ascending or descending. The parameter can be added only if the `sfdc:sortField` parameter is also present. By default, the search results are sorted in ascending order. This parameter isn’t used for relevance sorting. | # Requesting a Signed Request If your canvas app is set to use signed request for authentication, you can request a signed request on demand by using the SDK. Your app can ask Salesforce to resend the signed request that was used when your app was loaded or to send a new signed request. Requesting a signed request is useful when you are refreshing an expired session or getting authentication information after your app has been redirected. You can request a signed request on demand by using the `refreshSignedRequest()` or `repost()` JavaScript methods in the SDK. `refreshSignedRequest()` returns a new signed request via a callback, while `repost()` asks the parent window to initiate a new POST to your canvas app and reloads the app page with a refreshed signed request. Use these methods whenever you need to refresh the signed request for your app. Here are some example scenarios where you might need to refresh the signed request information. - The OAuth token within a signed request typically expires after two hours. If the OAuth token has expired, and you need to make additional API requests, you can call `refreshSignedRequest()` to get a new OAuth token without interrupting the user. - Canvas apps might need to use redirects, particularly when trying to provide single sign-on functionality across multiple systems. If your canvas app uses redirects, the redirect URL will not receive the original request body that contains the initial signed request information. You can use the new methods to request the signed request again. - In Summer ’14 and later, canvas apps can be user-approved apps. If your user-approved app has not been approved by the user, your app will not get an initial signed request POST. Instead, your app will need to be approved through OAuth, and then you can call `repost()` to get the signed request. Your canvas app must be configured to use signed request for authentication to use these methods. You’ll also need to reference canvas-all.js in your JavaScript code, as described in [Referencing the Canvas SDK](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-framework-referencing-sdk.md). After a request succeeds, your canvas app must verify the returned [SignedRequest](https://developer.salesforce.com/docs/platform/canvas-framework/reference/signed-request-object.md) information. For more information on verifying signed request information that is received from Salesforce, see [Verifying and Decoding a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-unsigning-code-example.md). ## Using `refreshSignedRequest()` to Obtain a Signed Request Use `refreshSignedRequest()` to request a new signed request via a callback that you provide. In this example, `refreshSignedRequest()` is called with a callback that checks the response code and then parses the signed request into the hashed Based64 context that is signed with the consumer secret and the Base64 encoded context itself. ```javascript // Gets a signed request on demand. Sfdc.canvas.client.refreshSignedRequest(function(data) { if (data.status === 200) { var signedRequest = data.payload.response; var part = signedRequest.split('.')[1]; var obj = JSON.parse(Sfdc.canvas.decode(part)); } } ``` ## Using `repost()` to Obtain a Signed Request Use `repost()` to instruct the parent window to send a new POST to your canvas app URL. The POSTcontains the signed request that was used when your app was loaded or a new signed request. Unlike `refreshSignedRequest()`, using `repost()` reloads the canvas app page. The following example calls `repost()`, asking for the original signed request. ```javascript // Gets a signed request on demand, without refreshing the signed request. Sfdc.canvas.client.repost(); ``` The following example calls `repost()`, asking for a new signed request. ```javascript // Gets a signed request on demand, first by refreshing the signed request. Sfdc.canvas.client.repost({refresh : true}); ``` **See Also** - [Signed Request Authentication](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-signed-req-authentication.md) - [SignedRequest](https://developer.salesforce.com/docs/platform/canvas-framework/reference/signed-request-object.md) - [Verifying and Decoding a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-unsigning-code-example.md) # Required Permissions for Change Event Subscribers Change Data Capture ignores sharing settings and sends change events for all records of a Salesforce object. To receive change events on a channel, the subscribed user must have one or more permissions depending on the entities associated with the change events. The permissions apply to Pub/Sub API and CometD subscribers but not to Apex triggers. Apex triggers run with system privileges under the Automated Process entity, so they don’t require those permissions. ## Change Event Permissions |To receive change events for|Required permission| |----------------------------|-------------------| |A specific standard or custom object:|View All Records for the object| |User:|View All Users| |Standard objects that don’t have the View All Records permission, such as Task and Event:|View All Data| |All entities on a channel:|View All Data (AND View All Users, if User is one of the entities)| ## Permission Enforcement For the standard `/data/ChangeEvents` channel and custom channels, user permissions are enforced on event delivery. Users can subscribe to the `/data/ChangeEvents` channel or to any custom channel regardless of their entity permissions. Users receive only change events associated with entities for which they have the necessary permissions and don't receive change events they don't have permissions for. If permissions change after subscription, the changes are enforced within 10 minutes for Pub/Sub API subscribers. For CometD subscribers, the changes aren't enforced until you restart the subscription. For the single-entity standard channels, which include change events for one standard or custom object, user permissions are enforced initially on subscription. If users don't have sufficient permissions for the corresponding object, the subscription is denied and an error is returned. If permissions change after successful subscription and users no longer have access to the entity, they stop receiving the corresponding change events. For more information about user permissions, see [View All and Modify All Permissions Overview](https://help.salesforce.com/articleView?id=users_profiles_view_all_mod_all.htm&type=5) in *Salesforce Help*. **See Also** - [Subscription Channels](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-subscribe-channels.md) - [*Pub/Sub API Guide*: Channel Membership and User Permission Changes](https://developer.salesforce.com/docs/platform/pub-sub-api/guide/considerations.html#channel-membership-and-user-permission-changes) # Reserved Characters The single quote (’) and backslash (\\) characters are reserved in SOQL queries and must be preceded by a backslash to be properly interpreted. Reserved characters, if specified in a `SELECT` clause as a literal string (between single quotes), must be escaped (preceded by the backslash \\ character) to be properly interpreted. An error occurs if you do not precede reserved characters with a backslash. The following characters are reserved: ```soql ' (single quote) \ (backslash) ``` For example, use the following SELECT statement to query the `Account.Name` field for “Bob's BBQ”: ```codesegment SELECT Id FROM Account WHERE Name = 'Bob\'s BBQ' ``` # Reset Self-Service User Password Initiates a password reset for a self-service user based on the specified user ID. The user’s current password becomes invalid and the user receives an email with a password reset link. To log in again, the user must finish resetting their password. This resource is available in REST API version 24.0 and later. Salesforce auto-generates a temporary password for the user and returns it in the response body. If the user can’t access the email link, they can finish resetting their password by logging in with the temporary password. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/SelfServiceUser/selfServiceUserId/password` **Formats:** JSON, XML **HTTP Method:** DELETE **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) # Reset User Password Initiates a password reset for a user based on the specified user ID. The user’s current password becomes invalid and the user receives an email with a password reset link. To log in again, the user must finish resetting their password. This resource is available in REST API version 24.0 and later. Salesforce auto-generates a temporary password for the user and returns it in the response body. If the user can’t access the email link, they can finish resetting their password by logging in with the temporary password. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/User/userId/password` **Formats:** JSON, XML **HTTP Method:** DELETE **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) # `resetPassword()` Changes a user's password to a temporary, system-generated value. ## Syntax ```java string password = connection.resetPassword(ID userID); ``` ## Usage Use [`resetPassword()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-resetpassword.md) to request that the API change the password of a [User](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) or [SelfServiceUser](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_selfserviceuser.htm), and return a system-generated password string of random letters and numbers. Use [`setPassword()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-setpassword.md) instead if you want to set the password to a specific value. Your client application must be logged in with sufficient access rights to change the password for the specified user. For more information, see [Factors that Affect Data Access](https://developer.salesforce.com/docs/platform/api/calls/calls.md). For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616). ## Sample Code—Java This sample resets the password for the user specified by the `userId` parameter. It calls `resetPassword()` with this ID and gets the temporary password from the call result. It writes this temporary password to the console and returns it. ```codesegment public String doResetPassword(String userId) { String result = ""; try { ResetPasswordResult rpr = connection.resetPassword(userId); result = rpr.getPassword(); System.out.println("The temporary password for user ID " + userId + " is " + result); } catch (ConnectionException ce) { ce.printStackTrace(); } return result; } ``` ## Sample Code—C# This sample resets the password for the user specified by the `userId` parameter. It calls `resetPassword()` with this ID and gets the temporary password from the call result. It writes this temporary password to the console and returns it. ```codesegment public String doResetPassword(String userId) { String result = ""; try { ResetPasswordResult rpr = binding.resetPassword(userId); result = rpr.password; Console.WriteLine("The temporary password for user ID " + userId + " is " + result); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } return result; } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`userID`|ID|ID of the [User](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) or [SelfServiceUser](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_selfserviceuser.htm) whose password you want to reset. For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616).| ## Response |Name|Type|Description| |----|----|-----------| |`password`|string|New password generated by the API. When the user logs in with this password, they’re asked to provide a new password. This password is temporary, meaning that it cannot be reused after the user has set their new password.| ## Fault [`InvalidIdFault`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [Utility Calls](https://developer.salesforce.com/docs/platform/api/guide/utility-calls.md) # Resizing a Canvas App Canvas provides methods for resizing a canvas app. Full reference documentation for these methods can be found in the [SDK](https://github.com/forcedotcom/salesforcecanvasframeworksdk) and [here](http://htmlpreview.github.io/?https://github.com/forcedotcom/SalesforceCanvasJavascriptSDK/blob/master/docs/index.html). - `autogrow`—Starts or stops a timer that checks the content size of the canvas iFrame and adjusts the frame. See [Automatically Resizing a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-autogrow-code-example.md). - `resize`—Informs the parent window to resize the canvas iFrame. See [Explicitly Resizing a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-resize-code-example.md). - `size`—Returns the current size of the canvas iFrame. See [Getting the Size of a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-size-code-example.md). - `subscribe`—Subscribes to parent events. Currently, `canvas.scroll` (of the parent) is the only supported parent event in the `canvas` namespace. See [Subscribing to Parent Events](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-subscribe-code-example.md). **note:** For resize functions to work with your canvas app, you must declare a DOCTYPE at the top of any HTML pages that are associated with the app. For example: ``. - **[Automatically Resizing a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-autogrow-code-example.md)** - **[Explicitly Resizing a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-resize-code-example.md)** - **[Getting the Size of a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-size-code-example.md)** - **[Subscribing to Parent Events](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-subscribe-code-example.md)** - **[Handling Orientation Changes in Your Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-orientation-code-example.md)** **See Also** - [Canvas SDK](https://developer.salesforce.com/docs/platform/canvas-framework/canvas-framework-using-sdk.md) # Resizing a Canvas App in a Visualforce Page The following code example shows how to call the `resize` method to explicitly set the height and width on a specific canvas app within a Visualforce page. ```java // Set the height and width explicitly and target a canvas app // Where 'mycanvas0' is the canvasId on the canvas component // var target = {canvas : "mycanvas0"}; Sfdc.canvas.controller.resize( {height : "1000px", width : "900px"}, target); ``` The following code example shows how to call the `resize` method to set the height on all canvas apps within a Visualforce page. ```java //Set only the height on all canvas apps Sfdc.canvas.controller.resize( {height : "1000px"}); ``` **See Also** - [Using Events between a Visualforce Page and a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-vf-app-resizing.md) - [Publishing a Canvas Event from a Visualforce Page](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-vf-publish-code-example.md) - [Subscribing to Events](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-vf-subscribe-code-example.md) - [Unsubscribing from Events in a Visualforce Page](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-vf-unsubscribe-code-example.md) # Resolve Lightning Locker Conflicts in Aura Sites Lightning Locker is enabled by default for all new Aura sites in Experience Cloud. However, occasionally a third-party component on the page or custom code in your `head` markup doesn’t work as expected due to a conflict with Lightning Locker. In such a situation, Salesforce recommends using one of the workarounds described here. ## Use JavaScript Custom Events Lightning Locker protects third-party components and custom code from interacting with resources from other namespaces, but not from the `head` markup. This limitation means that your `head` markup can contain custom code that bypasses Lightning Locker and introduces security vulnerabilities. Third-party scripts in the `head` element can also conflict with Salesforce platform code, leading to unpredictable issues. To address this limitation, isolate your third-party Aura and Lightning web components and custom code by using the `CustomEvent` constructor in your `head` markup. Third-party components and custom code can then interact with your resources without being responsible for loading or referencing that resource directly. Any data that must be passed through the event to the listener is passed in the `detail` property, which is created when initializing the event. The `detail` property is mapped to the dataLayer in your `head` markup listener. The custom events are then dispatched to any resource that extends `EventTarget`. For an example of using custom events, see [Adobe Analytics and Lightning Locker](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-security-locker-example.md). **note:** Be aware of the data that you’re passing with the JavaScript `CustomEvent` constructor, and ensure that your usage is secure. Any JavaScript running on your page, including any third-party App Exchange components that you’re using, can potentially listen for your event names and read this data. ## Set an Aura Component to API 39.0 If your third-party component or custom code doesn’t interact with an Aura component as expected, you can set the Aura component to Salesforce API version 39.0, which disables Lightning Locker for the component. See [Disable Lightning Locker for a Component](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/security_ls_disable.htm) in the *Lightning Aura Components Developer Guide*. **note:** Disabling Lightning Locker for an Aura component can introduce security flaws into your site and prevent the component from being available at design time or rendering at runtime. For consistency and ease of debugging, avoid having a parent Aura component and a child component on different API versions. Therefore, don’t use any Aura component set to API version 39.0 in a component hierarchy, such as a component within a component or a component that’s extending another component. If LWS is enabled in the org, setting API version 39.0 in the component doesn’t disable LWS for the component. However, LWS is likely to allow behaviors of components that Lightning Locker blocks, removing the need to disable it. ## Turn Off Lightning Locker **note:** Use this workaround only as a last resort. If you turn off Lightning Locker in your site, you disable it for *all* your site’s third-party components and custom code. The ramifications can be far-ranging and unexpected, such as introducing security flaws into your site. And if a third-party component hasn’t been [enabled to work without Lightning Locker](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-security-locker-off-components.md), it can prevent that component from being available at design time and rendering at runtime. When Lightning Locker is turned off, components from different namespaces can interact with and access each other’s Document Object Model (DOM), and restrictions around custom resources interacting with your site are relaxed. For more information on disabling Lightning Locker, see [Select a Security Level in Experience Builder Sites](https://help.salesforce.com/articleView?id=experience.networks_security_csp_scriptlevel.htm&type=5) in Salesforce Help. **note:** If LWS is enabled in the org, when you disable Lightning Locker in an Aura site, you actually disable LWS in the site. If you disable Lightning Locker in the LWR site, the site’s instance of LWS is disabled, even if LWS is enabled in the org. **See Also** - [ExperienceBundle for Experience Builder Sites](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-migrate-expbundle.md) - [*Experience Cloud Help*: Select a Security Level in Experience Builder Sites](https://help.salesforce.com/s/articleView?id=experience.networks_security_csp_scriptlevel.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) - [*Lightning Web Components Dev Guide*: Communicate with Events](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/events) - [*Lightning Aura Components Developer Guide*: Communicating with Events](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_intro.htm?search_text=events) # Resources by Version Lists available resources for the specified API version, including resource name and URI. ## Syntax **URI:** `/services/data/vXX.X/` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters:** none ## Example See [List Available REST Resources](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_discoveryresource.htm) # Response Bodies Successful execution of a request to a Salesforce Scheduler resource can return a response body either in JSON or XML format. For example, the request to get appointment time slots returns a list of available time slots for a selection of work type group and territories. - **[Time Slots](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-ls-timeslots.md)** Describes the result of Get Appointments Slots request. - **[Candidates](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-ls-candidates.md)** Describes the result of Get Appointments Candidates request. # Response: Elements The external search provider returns results to the federated search connector in Atom or RSS format. Common elements, such as from Salesforce or Dublin Core, are also provided. The federated search connector extracts only the specified elements. ## Feed Elements These fields are defined in the OpenSearch standard. The federated search connector extracts the value from these elements. - `` - `` ## Atom Entry Elements If the external search provider returns results in Atom 1.0 or 1.1 format, the federated search connector extracts only the specified elements for all record types. | Field | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `` | Required. Title of the search result. Limited to 255 characters, beyond which the text is truncated. | | `<id>` | Required. External ID of the search result. The ID can be reused to search for the corresponding specific record. Maximum length is 255 characters; if the length is longer, the entry is skipped. See the `{sfdc:searchById}` parameter in the URL Template request parameters for more details. | | `<link>` | Optional. Clickable, well-formatted URL link to open the external document. The federated search connector doesn’t encode this URL. The external search provider can proxy it to track clicks. Maximum length is 1,000 characters; otherwise, the entry is skipped. | | `<summary>` | Optional. Snippet for the search result. Can be replaced by `<content>`. Maximum length is 500 characters, beyond which the text is truncated. | | `<content>` | Optional. Snippet for the search result for text. Can be replaced by `<summary>`. Maximum length is 500 characters, beyond which the text is truncated. | | `<updated>` | Optional. Date of the last modification of the entry. [Follows the Atom date format](https://tools.ietf.org/html/rfc4287#section-3.3). For example: `2003-12-13T18:30:02.25+01:00`. | | `<published>` | Optional. Date of the creation of the entry. Follows the Atom date format. For example: `2003-12-13T18:30:02.25+01:00`. | ## Dublin Core Entry Elements For both Atom and RSS formats, the federated search connector also extracts Dublin Core elements if they are present. The following elements are defined in the [Dublin Core specification](http://dublincore.org/documents/2012/06/14/dcmi-terms/?v=elements) for the Dublin Core namespace `http://purl.org/dc/elements/1.1/` (dc). | Field | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------- | | `<dc:abstract>` | Optional. Snippet for the search result. Maximum length is 500 characters, beyond which the text is truncated. | | `<dc:date>` | Date of the content. Follows either the Atom or RSS date format. | | `<dc:description>` | Optional. Snippet for the search result. Maximum length is 500 characters, beyond which the text is truncated. | | `<dc:title>` | Optional. Title of the search result. Limited to 255 characters, beyond which the text is truncated. | ## RSS Entry Elements If the external search provider returns results in RSS 2.0 format, the federated search connector extracts only the specified elements for all record types. | Field | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `<description>` | Optional. Snippet for the search result. Maximum length is 500 characters, beyond which the text is truncated. | | `<guid>` | Only required if `<link>` not present. If `<guid>` is not present, `<link>` is used as the result URL and result ID as well. External ID of the search result. The ID can be reused to search for the corresponding specific record. Maximum length is 255 characters; if the length is longer, the entry is skipped. See the `{sfdc:searchById}` parameter in the URL Template request parameters for more details. | | `<link>` | Optional. Clickable, well-formatted URL link to open the external document. The federated search connector doesn't URL-encode this URL. The external search provider can proxy it to track clicks. Maximum length is 1,000 characters; if the length is longer, the entry is skipped. | | `<pubDate>` | Optional. The publication date for the content. Follows the RSS date format [RFC-822](https://tools.ietf.org/html/rfc822#section-5). For example: `Sat, 07 Sep 2002 0:00:01 GMT`. | | `<title>` | Required. Title of the search result. Limited to 255 characters, beyond which the text is truncated. | ## Salesforce Entry Elements For both Atom and RSS format, the federated search connector also extracts the following elements for all record types. | Field | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `<sfdc:recordType>` | Required if the external search provider uses Salesforce extensions; otherwise optional. Type of the result document. This element also includes additional fields provided for the result. It must have a single value listed by the `<sfdc:RecordTypes>` element of the OpenSearchDescription. Provided as text element, such as `<sfdc:recordType>BlogPost</sfdc:recordType>`. | | `<sfdc:link>` | Required if the external search provider uses the Salesforce extension; otherwise optional. If the external search provider uses Salesforce extensions, the URL should point to the app installed by the admin. This app then renders the external document inside Salesforce. This field represents a clickable link to open the external document within Salesforce. Might not be a well-formed URL. It isn’t URL-encoded by the federated search connector. Maximum length is 1,000 characters; if the length is longer, the entry is skipped. | ## Common Entry Elements These fields are custom and have been declared in the `OpenSearchDescription` with the `<sfdc:Field>` child element of `<sfdc:RecordType>`. A custom field value is provided as a text element. If a custom field has been declared with a name containing spaces, such as _Relevant Tags_, it can be referred to by replacing all spaces with underscores, such as `<sfdc:Relevant_Tags>`. Custom field maximum lengths depend on the type of field. A custom field is skipped if it exceeds the limit. Here are the limits for field types. The phone field type follows the E.123 standard, and the date field follows the Atom date format. | Field Type | Character Limit | | ---------- | --------------- | | string | 255 | | longstring | 500 | | number | 20 | | boolean | 10 | | percent | 20 | | currency | 20 | | email | 500 | | url | 1,000 | <!-- document id=d8e40f40eb329b4e4fa4914da877c793a3fd8d20b806d22f885f0cdc4c456840 url=/developer/current/en-us/platform/api-rest/guides/intro/intro-rest-architecture.md --> # REST API Architecture REST API follows the standard RESTful principles and characteristics. ## Client-server Client applications are independent from Salesforce REST API, meaning each is managed and updated independently. ## Stateless Each request from client to server must contain all the information necessary to understand the request, and not use any stored context on the server. However, the representations of the resources are interconnected using URIs, which allow the client to progress between states. ## Caching behavior Responses are labeled as cacheable or non-cacheable. ## Uniform interface All resources are accessed with a generic interface over HTTPS. ## Named resources All resources are named using a base URI that follows your Lightning Platform endpoint. See REST Resources and Requests for details and examples. ## Layered components Intermediaries, such as proxy servers and gateways, are allowed between the client and the resources. In addition to the standard RESTful principles, REST API includes other key characteristics in its architecture that are important to understand and consider as you develop your applications. ## Authentication REST API supports OAuth 2.0 (an open protocol to allow secure API authorization). See [Authorize Apps with OAuth](https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm) in *Salesforce Help* for more details. ## Support for JSON and XML JSON requests are supported in UTF-8 and are the default. XML requests are supported in UTF-8 and UTF-16. XML responses are provided in UTF-8. Use the `HTTP ACCEPT` header to specify either JSON or XML. In versions 57.0 and earlier, it’s possible to append `json` or `xml` to the URI. For example, `/Account/001D000000INjVe.json`. We recommend using the `HTTP ACCEPT` header to specify JSON or XML instead. In versions 58.0 and later, appending JSON or XML to the URI isn’t supported. ## Compression Compression reduces bandwidth loads by compressing the messages sent between REST API and your client. REST API supports compression with gzip and deflate, as defined by the HTTP 1.1 specification. See Compression Headers. ## Conditional Requests Response caching is supported by conditional request headers that follow the standards defined by the HTTP 1.1 specification, with a few exceptions. See Conditional Request Headers. ## Cross-Origin Resource Sharing Cross-Origin Resource Sharing (CORS) enables web browsers to request resources from origins other than their own. For example, using CORS, JavaScript code at https://www.example.com could request a resource from https://www.salesforce.com. To access supported Salesforce APIs, Apex REST resources, and Lightning Out from JavaScript code in a web browser, add the origin serving the code to a Salesforce CORS allowlist. See Perform Cross-Origin Requests from Web Browsers. ## Salesforce ID Length Salesforce IDs in response bodies are always 18-character IDs. In request bodies, you can use either 15 character IDs or 18 character IDs. ## Method Overriding To override an HTTP method if you use an HTTP library that doesn’t allow overriding or setting an arbitrary HTTP method name, use the request parameter `_HttpMethod`. ```nolang POST https://instance_name/services/data/v68.0/chatter/ /chatter/users/me/conversations/03MD0000000008KMAQ ?_HttpMethod=PATCH&read=true ``` **note:** The `_HttpMethod` parameter is case-sensitive. Use the correct case for all values. ## HTTPS All communication between client and server is over HTTPS. <!-- document id=cd258127d162e24e4d265be450c3b07e5f757538f96a372c90d77b3ac72206a3 url=/developer/current/en-us/platform/api-rest/guides/api-rest-pdf-archive.md --> # REST API 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_rest.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/api_rest.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/api_rest.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/api_rest.pdf) | <!-- document id=7218d56b7b81bf53fce65b1518addd8111e76004c13dd8fa5b101a918ace3e18 url=/developer/current/en-us/platform/caf-dev/guides/caf/caf-dev-examples-api-rest.md --> # REST API Examples Use REST API to create, update, or delete a record with Custom Address Fields data. **note:** Before you create a custom address field, review the [Custom Address Fields Requirements and Limitations](https://developer.salesforce.com/docs/platform/caf-dev/guide/caf-dev-limitations.md). To discuss the feature and ask questions, join the [Custom Address Fields Discussion](https://trailhead.salesforce.com/trailblazer-community/groups/0F94S000000H3KISA0) group on the Trailblazer Community. ## Create a New Account with Data in a Custom Address Field To create a new record, use the [sObject](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_basic_info.htm) resource. You supply the required field values in the request data, and send the request using the POST HTTP method. The response body contains the ID of the new record if the call is successful. This example creates an Account record which includes address data stored in the Mailing Address custom address field. **Example HTTP POST method to create a new Account** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/68.0/sobjects/Account -H "Authorization: Bearer token" -H "Content-Type: application/json" -d "@newaccount.json" ``` **Example request body newaccount.json file to create a new Account** ```nolang { "Name" : "Acme Incorporated", "Mailing_Address__City__s" : "Ahmedabad", "Mailing_Address__CountryCode__s" : "IN", "Mailing_Address__Street__s" : "102 Suryakoti", "Mailing_Address__PostalCode__s" : "380022", "Mailing_Address__StateCode__s": "GJ", "Mailing_Address__Latitude__s" : "37.775", "Mailing_Address__Longitude__s" : "-122.418", "Mailing_Address__GeocodeAccuracy__s" : "Address" } ``` **Example response body after successfully creating a new Account** ```nolang { "id" : "001XXXXXXXXXXXXXXX", "errors" : [ ], "success" : true } ``` ## Update Data Within a Custom Address Field on a Record To update a record, use the [sObject Rows](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_retrieve.htm) resource. Provide the updated record information in your request data and use the PATCH method of the resource with a specific record ID to update that record. Records in a single file must be of the same object type. This example updates the data stored in the Mailing Address custom address field for record ID `001XXXXXXXXXXXXXXX`. **HTTP PATCH example for updating an Account** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/68.0/sobjects/Account/001XXXXXXXXXXXXXXX -H "Authorization: Bearer token" -H "Content-Type: application/json" -d @patchaccount.json -X PATCH ``` **Example request body patchaccount.json file for updating the custom field, Mailing Address, on an Account** ```nolang { "Mailing_Address__City__s" : "Surendranagar", "Mailing_Address__CountryCode__s" : "IN", "Mailing_Address__Street__s" : "20 Udhyog Nagar", "Mailing_Address__PostalCode__s" : "363001", "Mailing_Address__StateCode__s": "GJ", "Mailing_Address__Latitude__s" : "22.757580", "Mailing_Address__Longitude__s" : "71.619350", "Mailing_Address__GeocodeAccuracy__s" : "Address" } ``` **Example response body after successfully updating an Account:** None returned ## Delete Data Within a Custom Address Field on a Record To delete address data stored within a custom address field on a record, update the record with the [sObject Rows](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_retrieve.htm) resource. Provide the updated record information in your request data and use the PATCH method of the resource with a specific record ID to update that record. Records in a single file must be of the same object type. This example deletes the data stored in the Mailing Address custom address field for record ID `001XXXXXXXXXXXXXXX`. **HTTP PATCH example for updating an Account** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/68.0/sobjects/Account/001XXXXXXXXXXXXXXX -H "Authorization: Bearer token" -H "Content-Type: application/json" -d @patchaccount.json -X PATCH ``` **Example request body patchaccount.json file for updating the custom field, Mailing Address, on an Account** ```nolang { "Mailing_Address__City__s" : null, "Mailing_Address__CountryCode__s" : null, "Mailing_Address__Street__s" : null, "Mailing_Address__PostalCode__s" : null, "Mailing_Address__StateCode__s": null, "Mailing_Address__Latitude__s" : null, "Mailing_Address__Longitude__s" : null, "Mailing_Address__GeocodeAccuracy__s" : null } ``` **Example response body after successfully updating an Account:** None returned ## Delete a Record That Contains Data in a Custom Address Field To delete records, use the [sObject Rows](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_retrieve.htm) resource. Specify the record ID and use the DELETE method of the resource to delete a record. When a record is deleted, all data for that record is deleted, including the custom address field information. This example deletes the Account record with ID `001XXXXXXXXXXXXXXX`. **HTTP DELETE example for updating an Account** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/68.0/sobjects/Account/001XXXXXXXXXXXXXXX -H "Authorization: Bearer token" -X DELETE ``` **Example request body:** None needed **Example response body after successfully updating an Account:** `200 OK` <!-- document id=19679b74f74272c60e09d7d6675b71e9339860a737fdd4e28b75f9dd0ae0c058 url=/developer/current/en-us/platform/api-rest/guides/intro/rest-rns.md --> # REST API Release Notes Use the Salesforce Release Notes to learn about the most recent updates and changes to REST API. For updates and changes that impact the Salesforce Platform, including REST API, see the [API Release Notes](https://help.salesforce.com/s/articleView?id=release-notes.rn_api.htm). When there are new or changed features in REST API, a link to those specific release notes is included here. Otherwise, refer to the API Release Notes for any recent changes that impact the platform and all APIs. <!-- document id=64d903241b542e6b3e60ba5e8c102ab16a6ce8a3abaec93d5ff849a06fb894c9 url=/developer/current/en-us/platform/api-rest/guides/intro/intro-rest-resources.md --> # REST Resources and Requests REST API is based on the usage of resources—pieces of data in Salesforce, such as records, collections of records, query results, metadata, or API information. Each resource is exposed by a uniform resource identifier (URI) and is accessed by sending HTTP requests to the corresponding URI. Depending on which resource you want to access and how you construct an HTTP request, you can perform several types of operations, including: - Determine available API versions - Access limits for your Salesforce org - Retrieve object metadata - Create, read, update, and delete records - Query and search for data You can send HTTP requests using a variety of software tools, which means that the exact appearance of a request can look different from the cURL examples in this guide. However, no matter how you submit requests, the elements don’t change. A typical request consists of these elements. - URI - HTTP method - Headers - Request body (not required for GET requests) ## URIs The URI is the path to a resource in Salesforce. Although the URI changes from resource to resource, the basic structure remains the same. ```nolang https://MyDomainName.my.salesforce.com/services/data/vXX.X/resource/ ``` Use `https://` to securely access resources. Replace `MyDomainName` with the subdomain of your Salesforce org. Salesforce runs on multiple server instances, so the examples in this guide use `MyDomainName` in place of a specific instance. Replace `XX.X` with the version of the API that you want to use, or use the `latest` alias (`/services/data/latest/resource/`) to automatically resolve to the most recently released API version. You can find a list of available versions by accessing the [Versions](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-versions.md) resource. Replace `resource` with the rest of the path to the resource. Depending on the resource, the path can contain parameters, such as IDs to identify a specific record. You can find the URIs for different resources in the Reference section of this guide. sObject resources access standard and custom objects in Salesforce. For information about objects, see [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/). **note:** Some parts of URIs are case-sensitive, such as IDs. Other parts of URIs aren't case-sensitive, such as object and field names. If your requests aren't successful, check that your URI has the right letter cases by comparing the URI to the examples in this guide. ## HTTP Methods REST API supports standard HTTP request methods (HEAD, GET, POST, PATCH, PUT, and DELETE), which follow the specifications at [https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html). The purpose of each method varies depending on the resource. For information on how and when to use each method, check the page for that resource in the Reference section of this guide. ## Headers Use headers to pass parameters and customize options for HTTP requests. REST API supports several standard HTTP headers, as well as custom headers that are specific to Salesforce. Common headers used in the examples include: - HTTP Accept—Indicates the format that your client accepts for the response body. Possible values are `application/json` and `application/xml`. If the value is missing or malformed, then `application/json` is used by default. - HTTP Content-type—Indicates the format of the request body that you attach to the request. Possible values are `application/json` and `application/xml`. - HTTP Authorization—Provides the OAuth 2.0 access token to authorize your client. REST API supports the Bearer authentication type. - Compression header—Compresses the request or the response. For more information, see [Compression Headers](https://developer.salesforce.com/docs/platform/api-rest/guide/intro-rest-compression.md). - Conditional request header—Validates the records that you access against a precondition. For more information, see [Conditional Request Headers](https://developer.salesforce.com/docs/platform/api-rest/guide/intro-rest-conditional-requests.md). ## Request Bodies A request body is a rich input that can be included in the request to provide additional information, such as field values for creating or updating records. A request body can be in JSON or XML format. **note:** Resources accessed with the GET method don’t require you to attach a request body. Use the HTTP Content-type header to indicate the file format of the request body. If you use cURL to send the request, attach the JSON or XML file to the request using the `—data-binary` or `-d` option. **See Also** - [Send REST Requests with cURL](https://developer.salesforce.com/docs/platform/api-rest/guide/intro-curl.md) - [Setting Up Your Java Developer Environment](https://developer.salesforce.com/docs/atlas.en-us.salesforce_developer_environment_tipsheet.meta/salesforce_developer_environment_tipsheet/salesforce_developer_environment_overview.htm) <!-- document id=004d6d3e25c5e4fa5456dbebe6c4e3dd6c07d23f6f831d7af55b36cd902f78ed url=/developer/current/en-us/platform/aura-platform/guides/aura/components/components-using-flow-resume.md --> # Resume a Flow Interview from an Aura Component By default, users can resume interviews that they paused from the Paused Interviews component on their home page. To customize how and where users can resume their interviews, embed the `lightning:flow` component in a custom Aura component. In your client-side controller, pass the interview ID into the `resumeFlow` method. ```javascript ({ init: function (component) { // Find the component whose aura:id is "flowData" var flow = component.find("flowData"); // In that component, resume a paused interview. Provide the method with // the ID of the interview that you want to resume. flow.resumeFlow("PAUSED_INTERVIEW_ID"); }, }); ``` This example shows how you can resume an interview—or start a new one. When users click **Survey Customer** from a contact record, the Aura component does one of two things. - If the user has any paused interviews for the Survey Customers flow, it resumes the first one. - If the user doesn’t have any paused interviews for the Survey Customers flow, it starts a new one. ```nolang <aura:component controller="InterviewsController"> <aura:handler name="init" value="{!this}" action="{!c.init}" /> <lightning:flow aura:id="flowData" /> </aura:component> ``` This Apex controller gets a list of paused interviews by performing a SOQL query. If nothing is returned from the query, `getPausedId()` returns a null value, and the component starts a new interview. If at least one interview is returned from the query, the component resumes the first interview in that list. ```apex public class InterviewsController { @AuraEnabled public static String getPausedId() { // Get the ID of the running user String currentUser = UserInfo.getUserId(); // Find all of that user's paused interviews for the Survey customers flow List<FlowInterview> interviews = [ SELECT Id FROM FlowInterview WHERE CreatedById = :currentUser AND InterviewLabel LIKE '%Survey customers%']; if (interviews == null || interviews.isEmpty()) { return null; // early out } // Return the ID for the first interview in the list return interviews.get(0).Id; } } ``` If the Apex controller returned an interview ID, the client-side controller resumes that interview. If the Apex controller returned a null interview ID, the component starts a new interview. ```javascript ({ init: function (component) { //Create request for interview ID var action = component.get("c.getPausedId"); action.setCallback(this, function (response) { var interviewId = response.getReturnValue(); // Find the component whose aura:id is "flowData" var flow = component.find("flowData"); // If an interview ID was returned, resume it in the component // whose aura:id is "flowData". if (interviewId !== null) { flow.resumeFlow(interviewID); } // Otherwise, start a new interview in that component. Reference // the flow's API Name. else { flow.startFlow("Survey_customers"); } }); //Send request to be enqueued $A.enqueueAction(action); }, }); ``` **See Also** - [_Component Library_: lightning:flow Component](https://developer.salesforce.com/docs/component-library/bundle/lightning:flow/documentation) <!-- document id=f6ba404c033e9827de8bfa0d44e42291e4da53a17829e9c27b5dd549aae784ec url=/developer/current/en-us/platform/platform-events/guides/platform-events/platform-events-subscribe-batch-resume.md --> # Resume a Platform Event Trigger After an Uncaught Exception Set a checkpoint in the event stream for where the platform event trigger resumes execution in a new invocation. If an Apex governor limit is hit or another uncaught exception is thrown, the checkpoint is used during the next execution of the trigger. Trigger processing resumes after the last successfully checkpointed event message. You can also set a checkpoint to explicitly control the number of events processed in one trigger execution. However, you can configure the trigger batch size more easily by using Metadata API or Tooling API. For more information, see [Configure the User and Batch Size for Your Platform Event Trigger with PlatformEventSubscriberConfig](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-trigger-config.md). By processing fewer event messages, your trigger is less likely to hit Apex governor limits. The maximum batch size of a platform event trigger is 2,000, while the maximum of an Apex object trigger is 200. Therefore, platform event triggers are more likely to reach limits and can benefit from this feature. To set a checkpoint for trigger resumption, set the replay ID of the last successfully processed event message using this method call. ```apex EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId); ``` When the trigger stops its flow of execution, either intentionally or because of an unhandled exception, such as a limit exception, it fires again with a new batch (the sObject list in `Trigger.New`). The new batch starts with the event message after the one with the replay ID that you set. The events are resent in their original order based on the ReplayID field values, which are unchanged. The trigger processes the resent events and later batches sequentially. The `setResumeCheckpoint(replayId)` method doesn’t cause the trigger execution to stop, but you can end the execution explicitly. For example, to control the batch size, end the execution flow after some event messages are processed. If the supplied Replay ID isn’t valid, the method throws an `EventBus.InvalidReplayIdException`. An invalid Replay ID is a replay ID that isn’t in the current trigger batch of events in the `Trigger.new` list. **note:** Resuming a batch in one trigger doesn’t affect another trigger on the same event object. However, having multiple triggers on the same object isn’t a best practice because we can’t guarantee the order of execution, so we recommend that you add only one trigger per object. **note:** For best practices and more code examples, see "Apply Best Practices for Writing Platform Event Triggers" in the [Platform Events Debugging](https://trailhead.salesforce.com/content/learn/modules/platform-events-debugging) Trailhead module. ## Example This example trigger sets the replay ID of the last processed event message in each iteration. If a limit exception occurs, the trigger is fired again and resumes processing starting with the event message after the one with the set replay ID. ```apex trigger ResumeEventProcessingTrigger on Low_Ink__e (after insert) { for (Low_Ink__e event : Trigger.New) { // Process the event message. // ... // Set the Replay ID of the last successfully processed event message. // If a limit is hit, the trigger refires and processing starts with the // event after the last one processed (the set Replay ID). EventBus.TriggerContext.currentContext().setResumeCheckpoint(event.replayId); } } ``` ## Example This example controls the platform event trigger batch size and matches it with the 200 batch size of Apex object triggers. The trigger counts the number of event messages processed. The `setResumeCheckpoint(replayId)` is called in each iteration of the loop after each event message that is successfully processed. The loop is exited if you exceed the count of 200 events, and the trigger stops execution. If you have unprocessed event messages, the trigger fires again. The list of event messages sent to the new trigger invocation starts with the event message after the one with the set replay ID. **note:** Starting in API version 51.0, you can configure the trigger batch size by using PlatformEventSubscriberConfig in Metadata API or Tooling API. For more information, see [Configure the User and Batch Size for Your Platform Event Trigger with PlatformEventSubscriberConfig](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-trigger-config.md). ```apex trigger ControlBatchSizeTrigger on Low_Ink__e (after insert) { Integer counter = 0; for (Low_Ink__e event : Trigger.New) { // Increase batch counter. counter++; // Only process the first 200 event messages if (counter > 200) { // Resume after the last successfully processed event message // after the trigger stops running. // Exit for loop. break; } // Process event message. // .... // Set Replay ID after which to resume event processing // in new trigger execution. EventBus.TriggerContext.currentContext().setResumeCheckpoint( event.ReplayId); } } ``` The `TestBatchSizeTriggerResumption` test class contains a test for the `ControlBatchSizeTrigger`. The test method in the class publishes 201 event messages. Next, it calls the `deliver()` method twice to fire the trigger twice. The first invocation processes 200 event messages. The second invocation processes the last event message. The test verifies that the trigger was invoked by inspecting the `EventBusSubscriber.Position` property, which holds the replay ID of the last processed event message. ```apex @isTest public class TestBatchSizeTriggerResumption { @isTest static void testResumingBatchSizeTrigger() { Test.startTest(); // Publish 201 test events List<Low_Ink__e> eventList = new List<Low_Ink__e>(); for(Integer i=0;i<201;i++) { Low_Ink__e oneEvent = new Low_Ink__e(Serial_Number__c='X-' + i); eventList.add(oneEvent); } Database.SaveResult[] srs = EventBus.publish(eventList); for(Database.SaveResult sr : srs) { System.assertEquals(true, sr.isSuccess()); } // Deliver the first 200 test event messages. // This will fire the associated event trigger. Test.getEventBus().deliver(); // Get old position of this subscriber EventBusSubscriber subOld = [SELECT Name, Position, Topic FROM EventBusSubscriber WHERE Topic='Low_Ink__e' AND Name='ControlBatchSizeTrigger']; System.debug(subOld); // Refire the trigger for the last event (201st). Test.getEventBus().deliver(); // VERIFICATION // Get new position of this subscriber EventBusSubscriber subNew = [SELECT Name, Position, Topic FROM EventBusSubscriber WHERE Topic='Low_Ink__e' AND Name='ControlBatchSizeTrigger']; System.debug(subNew); System.assertEquals(subOld.Position + 1, subNew.Position); Test.stopTest(); } } ``` <!-- document id=750323eb0856ac7f35e9eb7f9fb8c3457571f3e288a6d2d7dac9fa484102bde3 url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-event-resume.md --> # resume() Resumes event handling for this event from the same position in the event handler processing sequence from which it was previously paused. If the event isn’t paused, this method does nothing. This method throws an error if it’s called in the `"default"` phase. Any remaining event handlers might execute in the current call stack or might be deferred and executed in a new call stack. Therefore, the exact timing behavior is not predictable. ## Signature `resume()` <!-- document id=70c2cf2944e48f2e9f9ea2d2ccc03f9dc3d6ed90356724f8d907bb68c622edd6 url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-retrieve.md --> # retrieve() Retrieves one or more records based on the specified IDs. ## Syntax ```java sObject[] result = connection.retrieve(string fieldList, string sObjectType, ID ids[]); ``` ## Usage Use the `retrieve()` call to retrieve individual records from an object. The client application passes the list of fields to retrieve, the object, and an array of record IDs to retrieve. The `retrieve()` call doesn’t return records that have been deleted. In general, you use `retrieve()` when you know in advance the IDs of the records to retrieve. Use `query()` instead to obtain records when you don’t know the IDs or when you want to specify other selection criteria. Client applications can use `retrieve()` to perform a client-side join. For example, a client application can run a `query()` to obtain a set of [Opportunity](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_opportunity.htm) records, iterate through the returned opportunity records, obtain the `accountId` for each opportunity, and then call `retrieve()` to obtain [Account](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_account.htm) information for each `accountId`. Records for certain objects can’t be retrieved via the API. To retrieve a record via the `retrieve()` call, its object must be configured as retrievable (`retrieveable` is `true`). To determine whether an object can be retrieved, your client application can invoke the [`describeSObjects()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-describesobjects.md) call on the object and inspect its `retrievable` property. Your client application must be logged in with sufficient access rights to retrieve records within the specified object and to retrieve the fields in the specified field list. For more information, see [Factors that Affect Data Access](https://developer.salesforce.com/docs/platform/api/guide/calls.md). ## Sample Code—Java This sample retrieves the Id, Name, and Website of the specified Account records. It writes the fields of the retrieved records to the console. <!-- otherprops: java set_clipboard --> ```codesegment public void retrieveRecords(String[] ids) { try { SObject[] sObjects = connection.retrieve("ID, Name, Website", "Account", ids); // Verify that some objects were returned. // Even though we began with valid object IDs, // someone else might have deleted them in the meantime. if (sObjects != null) { for (int i = 0; i < sObjects.length; i++) { // Cast the SObject into an Account object Account retrievedAccount = (Account) sObjects[i]; if (retrievedAccount != null) { System.out.println("Account ID: " + retrievedAccount.getId()); System.out.println("Account Name: " + retrievedAccount.getName()); System.out.println("Account Website: " + retrievedAccount.getWebsite()); } } } } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample retrieves the Id, Name, and Website of the specified Account records. It writes the fields of the retrieved records to the console. <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void retrieveRecords(String[] ids) { try { sObject[] sObjects = binding.retrieve("ID, Name, Website", "Account", ids); // Verify that some objects were returned. // Even though we began with valid object IDs, // someone else might have deleted them in the meantime. if (sObjects != null) { for (int i = 0; i < sObjects.Length; i++) { // Cast the SObject into an Account object Account retrievedAccount = (Account)sObjects[i]; if (retrievedAccount != null) { Console.WriteLine("Account ID: " + retrievedAccount.Id); Console.WriteLine("Account Name: " + retrievedAccount.Name); Console.WriteLine("Account Website: " + retrievedAccount.Website); } } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`fieldList`|string|List of one or more fields in the specified object, separated by commas. You must specify valid field names and must have read-level permissions to each specified field. The fieldList defines the ordering of fields in the [`result`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-retrieve.md).| |`sObjectType`|string|Object from which to retrieve data. The specified value must be a valid object for your organization. For a complete list of objects, see [Standard Objects](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_list.htm).| |`ids`|ID[]|Array of one or more IDs of the objects to retrieve. You can pass a maximum of 2000 object IDs to the `retrieve()` call. For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616).| ## Response |Name|Type|Description| |----|----|-----------| |`result`|sObject[]|Array of one or more [sObjects](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject) representing individual records of the specified object. The number of sObject returned in the array matches the number of IDs passed into the `retrieve()` call. If you don’t have access to an object or if a passed ID is invalid, the array returns `null` for that object. For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616).| ## Faults [`InvalidSObjectFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidFieldFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [API Call Basics](https://developer.salesforce.com/docs/platform/api/guide/calls.md) <!-- document id=378d42238a748927613cbb13894f279df8f5d54501a853e536501ddf4b5f588e url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-retrieve-bulk.md --> # Retrieving Components in Bulk **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported.  If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. This target is the optimal way to download a large number of components of a single metadata type, such as custom reports, into a set of local files. The following parameters may be set for each `<sf:bulkRetrieve>` target: |Field|Description| |-----|-----------| |`username`|Required if `sessionId` isn’t specified. The Salesforce username used for login. The username associated with this connection must have the Modify Metadata through Metadata API Functions permission.| |`password`|Required if `sessionId` isn’t specified. The password you use to log in to the organization associated with this project. If you are using a security token, paste the 25-digit token value to the end of your password.| |`sessionId`|Required if `username` and `password` aren’t specified. The ID of an active Salesforce session or the OAuth access token. A session is created after a user logs in to Salesforce successfully with a username and password. Use a session ID for logging in to an existing session instead of creating a new session. Alternatively, use an access token for OAuth authentication. For more information, see [Authenticating Apps with OAuth](https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_authenticate.htm) in the Salesforce Help.| |`serverurl`|Optional. The Salesforce server URL (if blank, defaults to `login.salesforce.com`). To connect to a sandbox instance, change this value to `test.salesforce.com`.| |`retrieveTarget`|Required. The root of the directory structure into which the metadata files are retrieved.| |`metadataType`|Required. The name of the metadata type to be retrieved; for example, `CustomObject` for custom objects, or `Report` for custom reports. For a full list of allowed values, see [Component Types](https://developer.salesforce.com/docs/platform/salesforce-migration-guide/guide/daas-package.md).| |`containingFolder`|Optional. If the metadata is contained in a folder, this parameter should be the name of the folder from which the contents are retrieved.| |`batchSize`|Optional, defaults to 10. The number of items to retrieve while doing multi-part retrieve.| |`apiVersion`|Optional. The Metadata API version to use for the retrieved metadata files. The default is 68.0.| |`maxPoll`|Optional. Defaults to `200`. The number of times to poll the server for the results of the retrieve request. The clients waits for two seconds after the first poll attempt. The wait time is doubled for each successive poll attempt up to maximum of 30 seconds between poll attempts.| |`unzip`|Optional. Defaults to `true`. If set to `true`, the retrieved components are unzipped. If set to `false`, the retrieved components are saved as a zip file in the `retrieveTarget` directory.| To retrieve custom report components in bulk, specify a target in the build.xml file using `<sf:bulkRetrieve>`. ```xml <target name="bulkRetrieve"> <sf:bulkRetrieve username="${sf.username}" password="${sf.password}" sessionId="${sf.sessionId}" serverurl="${sf.serverurl}" metadataType="Report" retrieveTarget="retrieveUnpackaged"/> </target> ``` <!-- document id=bdd85ff4ada4199d301302318d8c5d743b9f170c63475eee9b78b598e39b2f2c url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-retrieve-packaged.md --> # Retrieving Managed or Unmanaged Packages **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. Packages are useful for distributing related bundles of metadata across multiple instances or organizations, via Lightning Platform AppExchange. However, you can use the Ant Migration Tool to freely retrieve and deploy packaged metadata without using AppExchange. You retrieve both managed and unmanaged packages in the same way. To retrieve a package, specify a `packageNames` parameter in the build.xml file. For example: ```xml <target name="retrieveNamedPackage"> <sf:retrieve username="${sf.username}" password="${sf.password}" sessionId="${sf.sessionId}" serverurl="${sf.serverurl}" retrieveTarget="projectFolder" packageNames="mySourcePackage"/> </target> ``` <!-- document id=df402b4c313292dea430d0336b6c801267a54f8de05fb7f70f3fdaff8137a06d url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-retrieve.md --> # Retrieving Metadata from a Salesforce Organization **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. To retrieve Lightning Platform components: 1. Open a command prompt. 2. Run Ant by specifying a target name in build.xml. If it’s the first time you’re running Ant, use `ant retrieveUnpackaged` to retrieve unpackaged components specified in package.xml. **note:** - The sample build.xml contains some useful targets for various `retrieve()` and `deploy()` options that you can modify or use as is. To see a list of all your named targets in build.xml, enter `ant -p` at the command line. - You can deploy or retrieve up to 10,000 files at once. The maximum size of the deployed or retrieved .zip file is 39 MB. If the files are uncompressed in an unzipped folder, the size limit is 600 MB or 629,145,600 bytes. The size limit in bytes is calculated as 600 x 1024 x 1024. If you’re working with many components, use the [`listMetadata`](https://developer.salesforce.com/docs/platform/salesforce-migration-guide/guide/forcemigrationtool-listmetadata.md) target to identify the subset of files that you want to retrieve. You can also retrieve batches of components as described in [Retrieving Components in Bulk](https://developer.salesforce.com/docs/platform/salesforce-migration-guide/guide/forcemigrationtool-retrieve-bulk.md#retrieving-components-in-bulk). <!-- document id=b444839db28909db7f862d0af5950acc0554c1d35a8033b1da22f54862d11fc9 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/javascript/pages-remote-objects-using-retrieve.md --> # Retrieving Records with Remote Objects Retrieve records by calling `retrieve()` on a Remote Objects model instance. `retrieve()` requires two arguments, one for query criteria and one for a callback handler. ```javascript RemoteObjectModel.retrieve({criteria}, callback_function) ``` `criteria` can be a Remote Objects query object or a function that returns one. The following two calls are equivalent. ```javascript var ct = new RemoteObjectModel(); // Empty callback functions for simplicity ct.retrieve({where: {FirstName: {eq: 'Marc' }}}, function() {}); // query object ct.retrieve(function(){ return({where: {FirstName: {eq: 'Marc' }}}); }, function() {}); // function returning query object ``` See [Format and Options for Visualforce Remote Objects Query Criteria](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-remote-objects-using-retrieve-query-object.md) for an explanation of the query object. `retrieve()` doesn’t return a result directly. The callback function enables you to handle the server response asynchronously. **note:** All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being completed, including handling returned results, must be placed in the callback function. Your callback function can accept up to three arguments. ```javascript function callback(Error error, Array results, Object event) { // ... } ``` See [Visualforce Remote Objects Callback Functions](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-remote-objects-callback-functions.md) for details about writing Remote Objects callback functions. To retrieve records using dates, pass in the JavaScript date object to the query. ```javascript var myDate = new Date('2017-01-20'); ct.retrieve({where: {CloseDate: {eq: myDate}}}, function() {}); ``` **See Also** - [Format and Options for Visualforce Remote Objects Query Criteria](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-remote-objects-using-retrieve-query-object.md) - [Visualforce Remote Objects Callback Functions](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-remote-objects-callback-functions.md) <!-- document id=0e3f72ed7549d8872e21ab1410df7df588ec6e6ea3c025afe981cfa78d120bfe url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-retrieve-unpackaged.md --> # Retrieving Unpackaged Components **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. The unpackaged package contains all of the standard objects, custom objects, Apex classes and other metadata components that exist natively in your organization, and not within a package. To retrieve unpackaged components, use a build.xml target that contains the unpackaged attribute that points to a package.xml file. For example: ```xml <target name="retrieveUnpackaged"> <mkdir dir="projectFolder"/> <sf:retrieve username="${sf.username}" password="${sf.password}" sessionId="${sf.sessionId}" serverurl="${sf.serverurl}" retrieveTarget="projectFolder" unpackaged="unpackaged/package.xml"/> </target> ``` The salesforce-ant.jar file contains Ant tasks for accessing the Metadata API. In the code above, `sf:retrieve` is an Ant task. The full list of metadata Ant tasks are described in the [Metadata API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/). <!-- document id=f68fbb0f94665440f976a1789605197906056f7b0772443942732e45a79d5ef7 url=/developer/current/en-us/platform/platform-events/guides/platform-events/platform-events-subscribe-apex-refire.md --> # Retry Event Triggers with EventBus.RetryableException Get another chance to process event notifications. Retrying a trigger is helpful when a transient error occurs or when waiting for a condition to change. Retry a trigger if the error or condition is external to the event records and is likely to go away later. **note:** Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain terms to avoid any effect on customer implementations. An example of a transient condition: A trigger adds a related record to a master record if a field on the master record equals a certain value. It’s possible that in a subsequent try, the field value changes and the trigger can perform the operation. To retry the event trigger, throw `EventBus.RetryableException`. Events are resent after a small delay. The delay increases in subsequent retries. If the trigger receives a batch of events, retrying the trigger causes all events in the batch to be resent. The events are resent in their original order based on the ReplayID field values, which are unchanged. The trigger processes the resent events and later batches sequentially. Resent events have the same field values as the original events, but the batch sizes of the events can differ. For example, the initial trigger can receive events with replay ID 10 to 20. The resent batch can be larger, containing events with replay ID 10 to 40. When the trigger is retried, the DML operations performed in the trigger before the retry are rolled back and no changes are saved. ## Limit the Number of Retry Attempts You can run a trigger up to 10 times when it’s retried (the initial run plus 9 retries). After the trigger is retried 9 times, it moves to the error state and stops processing new events. Events sent after the trigger moves to the error state and before it returns to the running state aren’t resent to the trigger. To resume event processing, fix the trigger and save it. We recommend limiting the retries to less than 9 times. Use the `EventBus.TriggerContext.currentContext().retries` property to check how many times the trigger has been retried. Alternatively, you can query the `EventBusSubscriber.retries` field in API version 43.0 and later. **note:** For more code examples, see "Apply Best Practices for Writing Platform Event Triggers" in the [Platform Events Debugging](https://trailhead.salesforce.com/content/learn/modules/platform-events-debugging) Trailhead module. ## Example This example is a skeletal trigger that gives you an idea of how to throw `EventBus.RetryableException` and limit the number of retries. The trigger uses an `if` statement to check whether a certain condition is true. Alternatively, you can use a try-catch block and throw `EventBus.RetryableException` in the catch block. ```apex trigger ResendEventsTrigger on Low_Ink__e (after insert) { if (condition == true) { // Process platform events. } else { // Ensure we don't retry the trigger more than 4 times if (EventBus.TriggerContext.currentContext().retries < 4) { // Condition isn't met, so try again later. throw new EventBus.RetryableException( 'Condition is not met, so retrying the trigger again.'); } else { // Trigger was retried enough times so give up and // resort to alternative action. // For example, send email to user. } } } ``` <!-- document id=b940c3c831e9fa95326b549821bd2a15f28e1951a39986c6a24dbce83f82b281 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-approvallayouts-process-head.md --> # Return Headers for a Single Approval Process on a Specified Object Returns only the headers that are returned by a GET request to sObject ApprovalLayouts resources. This gives you a chance to see header values before retrieving the content of the resource. Specify a particular approval process name to limit the request to one specific approval layout. This resource is available in REST API version 30.0 and later. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/describe/approvalLayouts/approvalProcessName` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/describe/approvalLayouts/ExampleApprovalProcessName -H "Authorization: Bearer token" ``` <!-- document id=78b730bbce532e94cc52140d23ce90a61785c13af702eda7e1bea83e1e1b84fe url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts-global-head.md --> # Return Headers for All Global Publisher Layouts Returns only the headers that are returned by a GET request to sObject Layouts resources. This gives you a chance to see header values ahead of time before retrieving the content of the resource. ## Syntax **URI:** `/services/data/vXX.X/sobjects/Global/describe/layouts/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Global/describe/layouts/ -H "Authorization: Bearer token" ``` <!-- document id=b18f22cf4583743df5c64283f848abb8023e64948005a7e993882c8381594c75 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-approvallayouts-head.md --> # Return Headers for Approval Layouts Returns only the headers that are returned by a GET request to sObject ApprovalLayouts resources. This gives you a chance to see header values before retrieving the content of the resource. This resource is available in REST API version 30.0 and later. ## Syntax **URI:** To return headers of a request for an approval layout description for a specified object, use `/services/data/vXX.X/sobjects/sObject/describe/approvalLayouts/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/describe/approvalLayouts/ -H "Authorization: Bearer token" ``` <!-- document id=c35bc26cef7b2adca3586eb285fb8db7b58b00373ca31a95a119ae2a7cbc3585 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-embeddedserviceconfigdescribe-head.md --> # Return Headers for Embedded Service Configuration Returns only the headers from a GET request to the Embedded Service Configuration Describe resource. This gives you a chance to see header values ahead of time before retrieving the content of the resource. You must be logged in to the account that owns the EmbeddedServiceConfigDeveloperName you are querying. This resource is available in REST API version 45.0 and later. ## Syntax **URI:** `/services/data/vXX.X/support/embeddedservice/configuration/embeddedServiceConfigDeveloperName` **Formats:** JSON **HTTP method:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None <!-- document id=c3c04606fbf84b55b58baa3e2bb0dce9ed19283475e21b0791df793c23bbd8b8 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-appmenu-head.md --> # Return Headers of App Menu Item Requests Returns only the headers that are returned by a GET request for the Salesforce app dropdown menu items. Use this URI to see the header values before you retrieve the content of the resource. This resource is available in REST API version 29.0 and later. ## Syntax **URI:** `/services/data/vXX.X/appMenu/AppSwitcher/` **Formats:** JSON, XML **HTTP method:** HEAD **Authentication:** `Authorization: Bearer token` **Request body:** None **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/appMenu/AppSwitcher -H "Authorization: Bearer token" ``` <!-- document id=85e652b699a869f05a83dc4890ddfc1788c903234874eafc480fb7712d390e02 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-appmenu-mobile-head.md --> # Return Headers of AppMenu Mobile Item Requests Returns only the headers that are returned by a GET request to the Salesforce mobile app for Android and iOS and the mobile web navigation menu. Use this URI to see the header values before you retrieve the content of the resource. This resource is available in REST API version 29.0 and later. ## Syntax **URI:** `/services/data/vXX.X/appMenu/Salesforce1/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request body:** None **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/appMenu/Salesforce1 -H "Authorization: Bearer token" ``` <!-- document id=eb6c6e08d512fa245dadea9d298b64b0dbe40bb1aa3895b96d09be6fdb0b923f url=/developer/current/en-us/platform/api-rest/guides/resources/resources-quickactions-head.md --> # Return Headers of Quick Actions Returns only the headers that are returned by sending a GET request to the Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. Add all required fields to an object before you create a quick action for that object. If you add a required field after creating a quick action, the field doesn’t appear in the quick action’s describe results. Then, when the quick action runs, the field isn’t available and an error occurs for the missing field. If you don’t want the required field to appear in the quick action’s layout, set a default value for the field. When working with actions, also refer to [sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions.md). **URI:** `/services/data/vXX.X/quickActions/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/quickActions/ -H "Authorization: Bearer token" ``` <!-- document id=94e9bdad2ab083961c3c7ae133659a8c5d6213ce83087a134bbe56096eb62fbf url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-compactlayouts-head.md --> # Return Headers Using sObject CompactLayouts Returns only the headers that are returned by a GET request to the sObject CompactLayouts resource. This gives you a chance to see header values ahead of time before retrieving the content of the resource. This resource is available in REST API version 29.0 and later. ## Syntax **URI:** For a compact layout description for a specific object, use `/services/data/vXX.X/sobjects/sObject/describe/compactLayouts/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/describe/compactLayouts -H "Authorization: Bearer token" ``` <!-- document id=3a0cbf7c8d26671e7fef53d63306188e85da535d5390894f4ab763cdf9b276f9 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-default-values-head.md --> # Return Headers Using sObject Quick Action Default Values Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/quickActions/actionName/defaultValues/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/quickActions/CreateContact/defaultValues/ -H "Authorization: Bearer token" ``` <!-- document id=c6508c5788f6a2c1c34101c7e414af4bd88bfcd7aacef0500065767088ceece0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-default-values-id-head.md --> # Return Headers Using sObject Quick Action Default Values by ID Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 29.0 and later. In API version 28.0, to evaluate the default values for an action, use `/services/data/vXX.X/sobjects/sObject/quickActions/action_name/defaultValues/parent_id`. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/quickActions/actionName/defaultValues/contextId` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/quickActions/CreateContact/defaultValues/001D000000JRWBd -H "Authorization: Bearer token" ``` <!-- document id=62823fbd6401cb45b25ccf8679d436c53f3cabd40a8344767904b72852f81b8a url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-detail-head.md --> # Return Headers Using sObject Quick Action Details Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/quickActions/actionName/describe/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/quickActions/CreateContact/describe/ -H "Authorization: Bearer token" ``` <!-- document id=12c838c7c3561ca52f2ce5cafbe4f2e69d2251f696f269175d8171e5777fb09b url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-head.md --> # Return Headers Using sObject Quick Actions Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. This resource returns all actions—both global and standard—in addition to the ones requested. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/quickActions/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/quickActions/ -H "Authorization: Bearer token" ``` <!-- document id=74eafc4e7c4997179a72289beb8b0428fa9ca7ef60e79f2be703a48576f41bc0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-upsert-head.md --> # Return Headers Using sObject Rows by External ID Returns only the headers that are returned by sending a GET request to the sObject Rows by External ID resource. This gives you a chance to see returned header values of the GET request before retrieving the content itself. **note:** For security reasons, some Top Level Domains (TLD) can conflict with certain file format extensions. Adjust your implementation to work around such cases. For example, using an email address, such as `example@email.inc`, as the External ID returns a “404 not found” error. There are several workarounds to handle conflicting TLDs. - Use a different External ID field. - Create a new External ID field that is the same as the email field and replace the "." with an "\_" to handle this case. - Run a query for emails ending in ".inc" to retrieve the record ID and use that for the upsert request. - Use SOAP API instead of REST API for upsert requests. - Accept the email as a query parameter instead of a path parameter by creating a custom Apex REST API. Use Apex to perform the upsert request. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/fieldName/fieldValue` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=c390a26067fe60c7e5c502668d34b587d8a25343dc476327b5c8d27e15039107 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-self-service-user-password-head.md --> # Return Headers Using sObject Self-Service User Password Returns only the headers that are returned by sending a GET request to the sObject Self-Service User Password resource. This operation allows you to see returned header values of the GET request before retrieving the content itself. This resource is available in REST API version 24.0 and later. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/SelfServiceUser/selfServiceUserId/password` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=0e2c49017521169b33ac3ef597073bb27ab37bbb207f87943a100f5d6bf20973 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-user-password-head.md --> # Return Headers Using sObject User Password Returns only the headers that are returned by sending a GET request to the sObject User Password resource. This operation allows you to see returned header values of the GET request before retrieving the content itself. This resource is available in REST API version 24.0 and later. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/User/userId/password` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=6a1b7b40d1e37beb53b40c7996f6a07ddb4385269141da5dfec5a00c087ff3d9 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-specific-action-head.md --> # Return Headers Using Specific sObject Quick Actions Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/quickActions/actionName` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/quickActions/CreateContact -H "Authorization: Bearer token" ``` <!-- document id=55562a2a6e4b9e5166dfd9eb21ed9391ba289e4571d10441bd88a6354b44c362 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-tabs-head.md --> # Return Headers Using Tabs Returns only the headers that are returned by a GET request to Tabs resources. This gives you a chance to see header values before retrieving the content of the resource. This resource is available in REST API version 31.0 and later. ## Syntax **URI:** `/services/data/vXX.X/tabs/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request body:** None **Request parameters:** None ## Example **Return headers of request for all tabs** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/tabs -H "Authorization: Bearer token" ``` <!-- document id=9d02baca45499fc16be59e834b70c893ea8a39c33303e55192bbb2c609d6e368 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-process-rule-object-head.md --> # Return HTTP Headers for a Process Rule of an sObject Returns only the headers that are returned by sending a GET request to the process rules resource for a specific process rule of an sObject. This gives you a chance to see returned header values of the GET request before retrieving the content. **URI:** `/services/data/vXX.X/process/rules/sObjectName/workflowRuleId` **Available since release:** 30.0 **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required **Example usage** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/process/rules/Account/01XXX000000/ -H "Authorization: Bearer token" ``` **Example request body:** None required **Example response body** ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=5e39d9cb17d19df30c0b45b1f070f460ffe169efa5c8801a21bc8f3a6636d27b url=/developer/current/en-us/platform/api-rest/guides/resources/resources-actions-invocable-custom-head.md --> # Return HTTP Headers for Custom Invocable Actions Returns only the headers that are returned by sending a GET request to the custom invocable actions resource. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 32.0 and later. ## URI `/services/data/vXX.X/actions/custom` ## Formats JSON, XML ## HTTP Methods HEAD ## Authentication `Authorization: Bearer token` ## Request parameters None required ## Example Example Request ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/actions/custom -H "Authorization: Bearer token" ``` Example Response Body ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=55118bcac79dc7b02e7e7cec6f9c7cb7861617b0fd29b54a58c1a848037651ac url=/developer/current/en-us/platform/api-rest/guides/resources/resources-actions-invocable-head.md --> # Return HTTP Headers for Invocable Actions Returns only the headers that are returned by sending a GET request to the invocable actions resource. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 32.0 and later. ## URI `/services/data/vXX.X/actions` ## Formats JSON, XML ## HTTP Methods HEAD ## Authentication `Authorization: Bearer token` ## Request parameters None required ## Example Example Request ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/actions -H "Authorization: Bearer token" ``` Example Response Body ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=d61b89427240cf9a718cbc195953d8ab983adb9029feb09420b7bb21c1e60727 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-process-approvals-head.md --> # Return HTTP Headers for Process Approvals Returns only the headers that are returned by sending a GET request to the process approvals resource. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 30.0 and later. ## Syntax **URI:** `/services/data/vXX.X/process/approvals/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/process/approvals/ -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=0be095f1ecbcca730d74456ef70567cf6bbe93f44d365f1f89c067e6c869c8a6 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-process-rules-head.md --> # Return HTTP Headers for Process Rules Returns only the headers that are returned by sending a GET request to the process rules resource. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 30.0 and later. ## Syntax **URI:** `/services/data/vXX.X/process/rules/` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/process/rules/ -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=a7bb00edd840f0027f4d539e6420d1536f6c731a21c4f48736b34fcaa44d561c url=/developer/current/en-us/platform/api-rest/guides/resources/resources-process-rules-object-head.md --> # Return HTTP Headers for Process Rules of an sObject Returns only the headers that are returned by sending a GET request to the process rules resource for all process rules of an sObject. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 30.0 and later. ## Syntax **URI:** `/services/data/vXX.X/process/rules/sObject` **Formats:** JSON, XML **HTTP methods:** HEAD **Authentication:** `Authorization: Bearer token` **Request parameters:** None required **Request body:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/process/rules/Account/ -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=cde60df55945d18328a2d63b50eefca4712ec6dde9a28a1bffe4e2a29d5e9fb7 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-actions-invocable-standard-head.md --> # Return HTTP Headers for Standard Invocable Actions Returns only the headers that are returned by sending a GET request to the standard invocable actions resource. This gives you a chance to see returned header values of the GET request before retrieving the content. This resource is available in REST API version 32.0 and later. ## Syntax ## URI `/services/data/vXX.X/actions/standard` ## Formats JSON, XML ## HTTP Methods HEAD ## Authentication `Authorization: Bearer token` ## Request parameters None required ## Example Example Request ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/actions/standard -H "Authorization: Bearer token" ``` Example Response Body ```nolang HTTP/1.1 200 OK Date: Mon, 21 Nov 2022 22:56:26 GMT ``` <!-- document id=d0dde119746d0dfa158a859e78aac7e247fb16cd2417559298eb3aa43eef2127 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts-head.md --> # Return Layout Headers for a Specified Object Returns only the headers that are returned by a GET request to sObject Layouts resources. This gives you a chance to see header values ahead of time before retrieving the content of the resource. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/describe/layouts/` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD --head https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Battle_Station__c/describe/layouts/ -H "Authorization: Bearer token" ``` <!-- document id=8b01e013b21ad0347e8d61cf716936337a84abf076c32b8d90aeda64150b0746 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts-multiple-rts-head.md --> # Return Layout Headers for an Object With Multiple Record Types Returns only the headers that are returned by a GET request to sObject Layouts resources. This gives you a chance to see header values ahead of time before retrieving the content of the resource. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/describe/layouts/recordTypeId` **Formats:** JSON, XML **HTTP Method:** HEAD **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example **Example Request** ```nolang curl -X HEAD https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Chocolate__c/describe/layouts/0125c000000oIN9AAM -H "Authorization: Bearer token" ``` <!-- document id=4311cbdb9060c4a7f4e5329ab4a15baf60c706540af187b96acfcd0bff92c1d9 url=/developer/current/en-us/platform/aura-platform/guides/aura/js/js-cmp-methods-async.md --> # Return Result for Asynchronous Code `aura:method` executes synchronously. Use the `return` statement to return a value from synchronous JavaScript code. JavaScript code that calls a server-side action is asynchronous. Asynchronous code can continue to execute after it returns. You can’t use the `return` statement to return the result of an asynchronous call because the `aura:method` returns before the asynchronous code completes. For asynchronous code, use a callback instead of a `return` statement. ## Step 1: Define `aura:method` in Markup Let’s look at an `echo` `aura:method` that uses a callback. We’ll use the `c:auraMethodCallerWrapper.app` and components outlined in [Calling Component Methods](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods.md). Here’s the `echo` `aura:method` in the `c:auraMethod` component. ```nolang <!-- c:auraMethod --> <aura:component controller="SimpleServerSideController"> <aura:method name="echo" description="Sample method with server-side call"> <aura:attribute name="callback" type="Function" /> </aura:method> <p>This component has an aura:method definition.</p> </aura:component> ``` The `echo` `aura:method` has an `aura:attribute` with a name of callback. This attribute enables you to set a callback that’s invoked by the `aura:method` after execution of the server-side action in `SimpleServerSideController`. ## Step 2: Implement `aura:method` Logic in Controller The `echo` `aura:method` invokes `echo()` in `auraMethodController.js`. Let’s look at the source. ```javascript /* auraMethodController.js */ ({ echo : function(cmp, event) { var params = event.getParam('arguments'); var callback; if (params) { callback = params.callback; } var action = cmp.get("c.serverEcho"); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { console.log("From server: " + response.getReturnValue()); // return doesn't work for async server action call //return response.getReturnValue(); // call the callback passed into aura:method if (callback) callback(response.getReturnValue()); } else if (state === "INCOMPLETE") { // do something } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } } }); $A.enqueueAction(action); }, }) ``` `echo()` calls the `serverEcho()` server-side controller action, which we’ll create next. **note:** You can’t return the result with a `return` statement. The `aura:method` returns before the asynchronous server-side action call completes. Instead, we invoke the callback passed into the `aura:method` and set the result as a parameter in the callback. ## Step 3: Create Apex Server-Side Controller The `echo` `aura:method` calls a server-side controller action called `serverEcho`. Here’s the source for the server-side controller. ```apex public with sharing class SimpleServerSideController { @AuraEnabled public static String serverEcho() { return ('Hello from the server'); } } ``` The `serverEcho()` method returns a `String`. ## Step 4: Call `aura:method` from Parent Controller Here’s the controller for `c:auraMethodCaller`. It calls the `echo` `aura:method` in its child component, `c:auraMethod`. ```javascript /* auraMethodCallerController.js */ ({ callAuraMethodServerTrip : function(component, event, helper) { var childCmp = component.find("child"); // call the aura:method in the child component childCmp.echo(function(result) { console.log("callback for aura:method was executed"); console.log("result: " + result); }); }, }) ``` `callAuraMethodServerTrip()` finds the child component, `c:auraMethod`, and calls its `echo` `aura:method`. `echo()` passes a callback function into the `aura:method`. The callback configured in `auraMethodCallerController.js` logs the result. ```javascript function(result) { console.log("callback for aura:method was executed"); console.log("result: " + result); } ``` ## Step 5: Add Button to Initiate Call to `aura:method` The `c:auraMethodCaller` markup contains a `lightning:button` that invokes `callAuraMethodServerTrip()` in `auraMethodCallerController.js`. We use this button to initiate the call to the `aura:method` in the child component. Here’s the markup for `c:auraMethodCaller`. ```nolang <!-- c:auraMethodCaller.cmp --> <aura:component > <p>Parent component calls aura:method in child component</p> <c:auraMethod aura:id="child" /> <lightning:button label="Call aura:method (server trip) in child component" onclick="{! c.callAuraMethodServerTrip}" /> </aura:component> ``` **See Also** - [Return Result for Synchronous Code](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods-sync.md) - [Calling Component Methods](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods.md) - [aura:method](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-tag-method.md) <!-- document id=205dbc6dd3eeb507407cf49ac03f1d96f94293a0490299df0dcfba9fbad4510f url=/developer/current/en-us/platform/aura-platform/guides/aura/js/js-cmp-methods-sync.md --> # Return Result for Synchronous Code `aura:method` executes synchronously. A synchronous method finishes executing before it returns. Use the `return` statement to return a value from synchronous JavaScript code. An asynchronous method can continue to execute after it returns. JavaScript code often uses the callback pattern to return a result after asynchronous code completes. We’ll describe later how to return a result for an asynchronous action. ## Step 1: Define `aura:method` in Markup Let’s look at a `logParam` `aura:method` that executes synchronous code. We’ll use the `c:auraMethodCallerWrapper.app` and components outlined in [Calling Component Methods](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods.md). Here’s the markup that defines the `aura:method`. ```nolang <!-- c:auraMethod --> <aura:component> <aura:method name="logParam" description="Sample method with parameter"> <aura:attribute name="message" type="String" default="default message" /> </aura:method> <p>This component has an aura:method definition.</p> </aura:component> ``` The `logParam` `aura:method` has an `aura:attribute` with a name of `message`. This attribute enables you to set a `message` parameter when you call the `logParam` method. The name attribute of `logParam` configures the `aura:method` to invoke `logParam()` in the client-side controller. An `aura:method` can have multiple `aura:attribute` tags. Each `aura:attribute` corresponds to a parameter that you can pass into the `aura:method`. For more details on the syntax, see [aura:method](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-tag-method.md). You don’t explicitly declare a return value in the `aura:method` markup. You just use a `return` statement in the JavaScript controller. ## Step 2: Implement `aura:method` Logic in Controller The `logParam` `aura:method` invokes `logParam()` in `auraMethodController.js`. Let’s look at that source. ```javascript /* auraMethodController.js */ ({ logParam : function(cmp, event) { var params = event.getParam('arguments'); if (params) { var message = params.message; console.log("message: " + message); return message; } }, }) ``` `logParam()` simply logs the parameter passed in and returns the parameter value to demonstrate how to use the `return` statement. If your code is synchronous, you can use a `return` statement; for example, you’re not making an asynchronous server-side action call. ## Step 3: Call `aura:method` from Parent Controller `callAuraMethod()` in the controller for `c:auraMethodCaller` calls the `logParam` `aura:method` defined in its child component, `c:auraMethod`. Here’s the controller for `c:auraMethodCaller`. ```javascript /* auraMethodCallerController.js */ ({ callAuraMethod : function(component, event, helper) { var childCmp = component.find("child"); // call the aura:method in the child component var auraMethodResult = childCmp.logParam("message sent by parent component"); console.log("auraMethodResult: " + auraMethodResult); }, }) ``` `callAuraMethod()` finds the child component, `c:auraMethod`, and calls its `logParam` `aura:method` with an argument for the message parameter of the `aura:method`. ```javascript childCmp.logParam("message sent by parent component"); ``` `auraMethodResult` is the value returned from `logParam`. ## Step 4: Add Button to Initiate Call to `aura:method` The `c:auraMethodCaller` markup contains a `lightning:button` that invokes `callAuraMethod()` in `auraMethodCallerController.js`. We use this button to initiate the call to `aura:method` in the child component. ```nolang <!-- c:auraMethodCaller.cmp --> <aura:component > <p>Parent component calls aura:method in child component</p> <c:auraMethod aura:id="child" /> <lightning:button label="Call aura:method in child component" onclick="{! c.callAuraMethod}" /> </aura:component> ``` **See Also** - [Return Result for Asynchronous Code](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods-async.md) - [Calling Component Methods](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-cmp-methods.md) - [aura:method](https://developer.salesforce.com/docs/platform/aura-platform/ref/ref-tag-method.md) <!-- document id=f00161f43313a67fbfd284e3a20a4b2cbad19e67b13cb53e6307adde5736b1b7 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/canvas-app-vf-component-record-fields.md --> # Returning Fields in the Record Object When you use the `<apex:canvasApp>` component to display a canvas app on a Visualforce page, and that page is associated with an object (placed on the page layout, for example), you can specify fields to be returned from the related object. To do this, use the `entityFields` attribute. You can use this attribute in one of the following ways. ## Return Specific Object Fields You can return specific object fields in the Record object by setting the `entityFields` attribute to a comma-separated list of field names. If there’s an invalid field name in the list, then that field name is ignored and the valid fields are returned in the Record object. ```nolang <apex:canvasApp applicationName="MyApp" entityFields="Phone,Fax,BillingCity" containerId="canvasAppDiv"/> ``` returns a Record object that looks like this: ```nolang "record":{ "attributes":{ "type":"Account", "url":"/services/data/v68.0/sobjects/Account/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO", "Phone":"(555) 555-5555", "Fax":"(555) 555-5555", "BillingCity":"Seattle" } ``` ## Return All Object Fields You can return all object fields in the Record object by setting the `entityFields` attribute to the wildcard "\*". ```nolang <apex:canvasApp applicationName="MyApp" entityFields="*" containerId="canvasAppDiv"/> ``` returns a Record object that looks like this: ```nolang "record":{ "attributes":{ "type":"Account", "url":"/services/data/v68.0/sobjects/Account/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO", "IsDeleted":false, "MasterRecordId":null, "Name":"Edge Communications", "Type":"Customer - Channel", "ParentId":null, "BillingStreet":"123 Main Street", "BillingCity":"Seattle", "BillingState":"WA", "BillingPostalCode":"98121", "BillingCountry":"USA", ... } ``` ## Return the Id Field If the `<apex:canvasApp>` component doesn’t have the `entityFields` attribute or if the attribute is blank, then only the Id field is returned in the Record object. ```nolang <apex:canvasApp applicationName="MyApp" containerId="canvasAppDiv"/> ``` returns a Record object that looks like this: ```nolang "record":{ "attributes":{ "type":"Account", "url":"/services/data/v68.0/sobjects/Account/001xx000003DGWiAAO" }, "Id":"001xx000003DGWiAAO" } ``` **See Also** - [apex:canvasApp Component](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-vf-component-ref.md) - [Record](https://developer.salesforce.com/docs/platform/canvas-framework/reference/record-object.md) - [Controlling Canvas App Behavior](https://developer.salesforce.com/docs/platform/canvas-framework/guide/lifecycle/canvas-controlling-app-behavior.md) <!-- document id=06a69d4bc41bc63901f745d504af1ab3dea665100067df68fd9588763fa84a9b url=/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-sosl-returning.md --> # RETURNING _FieldSpec_ `RETURNING` is an optional clause that you can add to a SOSL query to specify the information to be returned in the text search result. If you don’t specify this clause, the default behavior is to return the IDs of all searchable objects in advanced search up to the maximum limit. The maximum limit is specified in the `LIMITn` clause or 2,000 (API version 28.0 and later), whichever is smaller. The returned IDs include custom objects even if there’s no custom tab. Search results list objects in the order specified in the clause. API version 27.0 and earlier support a maximum of 200 results. **note:** External objects, articles, documents, feed comments, feed items, files, products, and solutions must be specified explicitly in a `RETURNING` clause to be returned in search results. For example: ```soql FIND {MyProspect} RETURNING MySampleExternalObject, KnowledgeArticleVersion, Document, FeedComment, FeedItem, ContentVersion, Product2, Solution ``` Use the `RETURNING` clause to restrict the results data that is returned from the search() call. ## Syntax In the following syntax statement, square brackets [] represent optional elements that can be omitted. A comma indicates that the indicated segment can appear more than one time. ```soql RETURNING ObjectTypeName [(FieldList [WHERE] [USING Listview=_listview name] [ORDER BY Clause] [LIMIT n] [OFFSETn])] [, ObjectTypeName [(FieldList [WHERE] [ORDER BY Clause] [LIMITn] [OFFSETn])]] ``` RETURNING can contain the following elements: | Name | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ObjectTypeName` | Object to return. If specified, then the search() call returns the IDs of all found objects matching the specified object. Must be a valid sObject type. You can specify multiple objects, separated by commas. If you specify more than one `ObjectTypeName`, each object must be distinct; you can't repeat an `ObjectTypeName` within a single `RETURNING` clause. The search() call only returns objects specified in the `RETURNING` clause. | | `FieldList` | Optional list of one or more fields to return for a given object, separated by commas. If you specify one or more fields, the fields are returned for all found objects. If you want to use relationship fields, the format and supported depth is the same as SOQL. | | `USING ListView=` | Optional clause used to search within a single given object’s list view. Only one list view can be specified. Only the first 2,000 records of the list view are searched, according to the sort order the user has set for the list view. `ListView=Recent` searches for the most recently accessed items viewed or referenced by the current user. | | `WHERE` | Optional description of how search results for the given object are filtered, based on individual field values. If unspecified, the search retrieves all the rows in the object that are visible to the user. If you want to specify a `WHERE` clause, you must include a `FieldList` with at least one specified field. See [conditionExpression](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-where.md) for more information. | | `ORDER BY Clause` | Optional description of how to order the returned result, including ascending and descending order, and how nulls are ordered. You can supply more than one `ORDER BY` clause. If you want to specify an `ORDER BY` clause, you must include a `FieldList` with at least one specified field. | | `LIMITn` | Optional clause that sets the maximum number of records returned for the given object. If unspecified, all matching records are returned, up to the limit set for the query as a whole. If you want to specify a `LIMIT` clause, you must include a `FieldList` with at least one specified field. | | `OFFSETn` | Optional clause used to specify the starting row offset into the result set returned by your query. `OFFSET` can be used only when querying a single object. `OFFSET` must be the last clause specified in a query. If you want to specify an `OFFSET` clause, you must include a `FieldList` with at least one specified field. | Invalid `WHERE` syntax (missing `FieldList`): ```soql RETURNING Account (WHERE name like 'test') ``` Valid `WHERE` syntax: ```soql RETURNING Account (Name, Industry WHERE Name like 'test') ``` Invalid `ORDER BY` syntax (missing `FieldList`): ```soql RETURNING Account (ORDER BY id) ``` Valid `ORDER BY` syntax: ```soql RETURNING Account (Name, Industry ORDER BY Name) ``` Invalid `LIMIT` syntax (missing `FieldList`): ```soql RETURNING Account (LIMIT 10) ``` Valid `LIMIT` syntax: ```soql RETURNING Account (Name, Industry LIMIT 10) ``` Invalid `OFFSET` syntax (missing `FieldList`): ```soql RETURNING Account (OFFSET 25) ``` Valid `OFFSET` syntax: ```soql RETURNING Account (Name, Industry OFFSET 25) ``` **note:** The `RETURNING` clause affects whether external objects are searched. For other objects, the `RETURNING` clause affects what data is returned, not what data is searched. The `IN` clause affects what data is searched. ## Example RETURNING Clauses | Search Type | Examples | | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | No Field Spec | `FIND {MyProspect}` | | One sObject, no fields | `FIND {MyProspect} RETURNING Contact` | | Multiple sObject objects, no fields | `FIND {MyProspect} RETURNING Contact, Lead` | | One sObject , one or more fields | `FIND {MyProspect} RETURNING Account(Name)` | | | `FIND {MyProspect} RETURNING Contact(FirstName, LastName)` | | Custom sObject | `FIND {MyProspect} RETURNING CustomObject_c` | | | `FIND {MyProspect} RETURNING CustomObject_c(CustomField_c)` | | Multiple sObject objects, one or more fields, limits | `FIND {MyProspect} RETURNING Contact(FirstName, LastName LIMIT 10), Account(Name, Industry)` | | Multiple sObject objects, mixed number of fields | `FIND {MyProspect} RETURNING Contact(FirstName, LastName), Account, Lead(FirstName)` | | Unsearchable sObject objects | `FIND {MyProspect} RETURNING RecordType` | | | `FIND {MyProspect} RETURNING Pricebook` | | Invalid sObject objects | `FIND {MyProspect} RETURNING FooBar` | | Invalid sObject field | `FIND {MyProspect} RETURNING Contact(fooBar)` | | Single object limit | `FIND {MyProspect} RETURNING Contact(FirstName, LastName LIMIT 10)` | | Multiple object limits and a query limit | `FIND {MyProspect} RETURNING Contact(FirstName, LastName LIMIT 20), Account(Name, Industry LIMIT 10), Opportunity LIMIT 50` | | Single object offset | `FIND {MyProspect} RETURNING Contact(FirstName, LastName OFFSET 10)` | | List view | `FIND {MyAcccount} IN ALL FIELDS RETURNING Account(Id, Name USING ListView=ListViewName)` | **note:** Apex requires that you surround SOQL and SOSL statements with square brackets to use them in your statements. You can use Apex script variables and expressions when preceded by a colon (`:`). **See Also** - _[SOQL and SOSL reference_: Understanding Relationship Fields and Polymorphic Fields](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-relationships-and-polymorph-keys.md) <!-- document id=b4a5e5c75a872062187b7366290a9923a09d2f8d15b5e5c179eef6edb70af896 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-review-approval-work-item.md --> # Review Approval Work Item Action Update an approval work item status with the assignee or reviewer's decision and any comments that the assignee or reviewer added. Keep these considerations in mind when you use this invocable action. - The user must be an assignee of the approval work item or be a member of a group or queue if the approval work item is assigned to the group or queue. Additionally, a user has access to Approval Submissions if they're a delegate of the assignee or has a role higher than the assignee. - The status of the approval work item must be in `Assigned` status. - The user can also use this action if inherited access to group or queue membership, nested group membership, roles hierarchy, or delegates is available. See [Public Group Considerations](https://help.salesforce.com/s/articleView?id=platform.user_groups_considerations.htm). This action is available in API version 62.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v68.0/actions/standard/reviewApprovalWorkItem` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`approvalDecision`|string|Required. Action that the assigned approver made for the approval work item. Valid values: `approve` or `reject`.| |`approvalWorkItemId`|string|Required. ID of the approval work item to be reviewed by the assigned approver.| |`channelType`|picklist|Type of channel where the request to review the approval work item originated. Valid values: `InvocableAction`, `Slack`, or `ApprovalRecord`. The default value is `InvocableAction`. Available in API version 65.0 and later.| |`comments`|string|Approval comments for the decision.| ## Outputs None. ## Example **POST** Here's a sample request for the Review Approval Work Item action. ```nolang { "inputs": [ { "approvalWorkItemId": "9jRxx00000001lhEAA", "approvalDecision": "Approve", "channelType": "InvocableAction", "comments": "Looks good." } ] } ``` Here's a sample response for the Review Approval Work Item action. ```nolang { "actionName": "reviewApprovalWorkItem", "errors": null, "invocationId": null, "isSuccess": true, "outcome": null, "outputValues": null, "sortOrder": -1, "version": 1 } ``` <!-- document id=4f2b0b58dca30351c7c0efea11fdc33b0d1abc3f45bd8a3342efcc1077c3ab28 url=/developer/current/en-us/platform/data-loader-impl/guides/data-loader/reviewing-output-files.md --> # Review Data Loader Output Files After an import or export, Data Loader generates two CSV output files that contain the results of the operation. One file name begins with `success`, and the other starts with `error`. Both files have the extension `.csv`. Use the Data Loader CSV file viewer to open the files. Specify the folder containing `success` and `error` CSV files in the `Finish` step of an operation. ## Before You Begin **note:** Export operations don’t generate a success file by default. To generate a success file when exporting data, check **Generate status files for exports** in the Advanced Settings dialog. 1. Choose **View** | **View CSV**. 2. Specify the number of rows to view. Each row in the CSV file corresponds to one Salesforce record. The default is 1,000. 3. To view a specific CSV file, click **Open CSV**. To view the last success file, click **Open Success**. To view the last error file, click **Open Error**. 4. To open the file in an external program, such as Excel, click **Open in External Program**. The success file contains the successfully loaded records, including a column with the newly generated record IDs. The error file contains the rejected records, with a column that describes why the load failed. If the object you’re exporting has a column named “success” or “error”, your output file columns could display incorrect information. To avoid this problem, rename the columns. 5. To return to the CSV Chooser window, click **Close**. To exit the window, click **OK**. To generate success files when exporting data, select `Generate status files for exports`. <!-- document id=f683c98c44dcfee5af1556ad80c79f995172e840fff15813fa46ea12075c0e4f url=/developer/current/en-us/platform/api-streaming/guides/api-streaming/generic-streaming/create-java-client-oauth.md --> # Run a Java Client with OAuth Bearer Token Login Run a Java client that uses EMP Connector to subscribe to the channel with OAuth authentication. 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/code-examples/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. Get the EMP Connector project from GitHub. See [Step 3: Download and Build the Project](https://developer.salesforce.com/docs/platform/api-streaming/code-examples/code-sample-java-download-jars.md). 2. 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. 3. Run the `BearerTokenExample` class, and provide the following argument values. | Argument | Value | | -------- | ---------------------------------------------- | | username | Username of the logged-in user. | | password | Password for the username (or logged-in user). | | channel | `/u/notifications/ExampleUserChannel` | 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. 4. When you run this client app and generate notifications using the REST resource, the output will look something like: ```nolang Subscribed: Subscription [/u/notifications/ExampleUserChannel:-1] Received: {payload=Broadcast message to all subscribers, event={createdDate=2016-12-13T00:57:36.020Z, replayId=1}} Received: {payload=Another message, event={createdDate=2016-12-13T00:58:16.591Z, replayId=2}} ``` In the next step, you learn how to generate notifications using REST. <!-- document id=91e486892782d7dcd247066f3709bbc5960d9f5d71cc356854e5a5bf52b9e79d url=/developer/current/en-us/platform/api-streaming/guides/api-streaming/generic-streaming/create-java-client.md --> # Run a Java Client with Username and Password Login Run a Java client that uses EMP Connector to subscribe to the channel with username and password authentication. 1. Get the EMP Connector project from GitHub. See [Step 3: Download and Build the Project](https://developer.salesforce.com/docs/platform/api-streaming/code-examples/code-sample-java-download-jars.md). 2. In the /src/main/java/com/salesforce/emp/connector/example folder, open the [LoginExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/LoginExample.java) source file. 3. Run the `LoginExample` class and provide arguments. | Argument | Value | | -------- | ---------------------------------------------- | | username | Username of the logged-in user. | | password | Password for the username (or logged-in user). | | channel | `/u/notifications/ExampleUserChannel` | 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. 4. When you run this client app and generate notifications using the REST resource, the output will look something like: ```nolang Subscribed: Subscription [/u/notifications/ExampleUserChannel:-1] Received: {payload=Broadcast message to all subscribers, event={createdDate=2016-12-13T00:57:36.020Z, replayId=1}} Received: {payload=Another message, event={createdDate=2016-12-13T00:58:16.591Z, replayId=2}} ``` Generally, don’t handle usernames and passwords of others when running code in production. In a production environment, delegate the login to OAuth. The next step connects to Streaming API with OAuth. <!-- document id=68b7c437b34984307a09ab3f02ebf7b2ddb4f3ac9704e00e7c13d8a79276f7f1 url=/developer/current/en-us/platform/data-loader-impl/guides/data-loader/using-the-command-line-interface.md --> # Run Batch File With Windows Command-Line Interface For automated batch operations, such as nightly scheduled loads and extractions, run Data Loader from the Windows command-line. ## Before You Begin To run Data Loader from a configured Windows batch file: **note:** The Data Loader command-line interface is supported for Windows only. 1. Include your encrypted password in the configuration file to run a batch operation. For more information, see [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) and [Encrypt from the Command Line](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/loader-encryption.md). 2. Use the process-conf.xml file to configure batch file processing. Specify the name of the process in the `ProcessRunner` bean's `id` attribute. For example, ```nolang <bean id="accountInsert" class="com.salesforce.dataloader.process.ProcessRunner" scope="prototype"> ``` 3. Navigate to the Data Loader \bin directory by entering this command. Replace the file path with the path from your system. C:\Users\{userName}\dataloader\_version_\bin 4. To run the batch file, use the correct command syntax for `process.bat`: ```nolang process.bat <configdir> [<operation>] ``` where: - `<configdir>` (mandatory) The absolute or relative path to the directory containing process-conf.xml. It must be the first parameter when running `process.bat`. - `<batch process bean id>` (optional) The id of the batch process bean of `class com.salesforce.dataloader.process.ProcessRunner` defined in the process-conf.xmlfile. If not provided, then the value of the `process.name` property in the config.properties file is used. ## Running `process.bat` using both parameters To execute Data Loader in batch mode, we’ll use the beans, their properties and attributes specified for a `ProcessRunner` bean with `id="accountInsert"` in the process-conf.xml file located in C:\Users\username\dataloaderconfig directory. ```nolang process.bat "C:\Users\username\dataloaderconfig" accountInsert ``` ## Next Steps **tip:** If you experience login issues in the command-line interface after upgrading Data Loader, try encrypting your password again to solve the problem. <!-- document id=6fd255d6a012a6de114b136766b00b66aa72ba832ebc1b272b5e05baaaf3f491 url=/developer/current/en-us/platform/data-loader-impl/guides/data-loader/loader-batchmode-intro.md --> # Run in Batch Mode (Windows Only) You can run Data Loader in batch mode from the Windows command line. Batch mode runs a series of Data Loader processes in a certain order using a batch file. You can rerun the same sequence of processes using an executable .bat file. |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| We recommend that you set the `JAVA_HOME` environment variable to the directory where Zulu OpenJDK is installed. Doing so ensures that you can run Data Loader in batch mode from the command line. **note:** The Data Loader command-line interface is supported for Windows only. **note:** If you’re batch mode from the command line with a version earlier than 8.0, upgrade your batch mode interface. <!-- document id=b556efdf432e654d8747f021eab9949b28a66e3a85e903b2444335d076411dd2 url=/developer/current/en-us/platform/data-loader-impl/guides/data-loader/loader-runprocess.md --> # Run Individual Batch Processes You can run one batch process at a time. To start an individual batch process, use \bin\process.bat. The command-line requires the following parameters. - Configuration directory—The default is \conf. To use an alternate directory, create a directory and add these files to it. - If your process is not interactive, copy process-conf.xml from \samples\conf. - If your process requires database connectivity, copy database-conf.xml from \samples\conf. - Copy config.properties from \conf. - Process name—The name of the ProcessRunner bean from \samples\conf\process-conf.xml. Process Example ```nolang process ../conf accountMasterProcess ``` **note:** To view tips and instructions, add `-help` to the command contained in process.bat. **note:** You can configure external process launchers, such as the Windows XP Scheduled Task Wizard, to run processes on a schedule. <!-- document id=db35b3d520756dfcfa2f3a6daa57b8cbd925b04f90a996703bbec4f06d102841 url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-deploy-run-local-tests.md --> # Run the Same Tests in Sandbox and Production Deployments Starting in API version 34.0, you can choose which tests to run in your development environment, such as only local tests, to match the tests run in production. In earlier versions, if you enabled tests in your sandbox deployment, you couldn’t exclude managed package tests. **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. By default, no tests are run in a deployment to a non-production organization, such as a sandbox or a Developer Edition organization. To specify tests to run in your development environment, set a [`testLevel` deployment option](https://developer.salesforce.com/docs/platform/salesforce-migration-guide/guide/forcemigrationtool-deploy.md). For example, to run local tests in a deployment and to exclude managed package tests, add the `testLevel="RunLocalTests"` parameter to the deploy target as shown in this example. ```xml <target name="deployCode"> <sf:deploy username="${sf.username}" password="${sf.password}" sessionId="${sf.sessionId}" serverurl="${sf.serverurl}" deployroot="codepkg" testLevel="RunLocalTests"> </sf:deploy> </target> ``` **note:** The `RunLocalTests` test level is enforced regardless of the contents of the deployment package. In contrast, tests are executed by default in production only if your deployment package contains Apex classes or triggers. You can use `RunLocalTests` for sandbox and production deployments. <!-- document id=84288f5982cd96006f392eb7b4fd0916e9970027b5fb8eb3609edb130a3a616c url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/quick-start/quick-start-run-the-app-locally.md --> # Run the Web App Locally In this step, you’ll package the Web app using Maven and then run it locally using Jetty. When you package the Web app, the process downloads all the components needed to run the Web app, including Jetty. 1. Open a command window and navigate to c:\SalesforceCanvasFrameworkSDK. 2. Enter the command `mvn package`. You’ll see output in the command window as Maven packages the app and its dependent components. If the process completes successfully, you’ll see something like this: ```nolang [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 28.016s [INFO] Finished at: Tue Jul 03 08:00:42 PDT 2012 [INFO] Final Memory: 8M/59M [INFO] ------------------------------------------------------------------------ ``` 3. To use Jetty to run the app, you’ll need to enable local SSL support. This step only needs to be done once per app, so if you’ve already done this, skip this step. Ensure that the command window is open and you’re in the directory c:\SalesforceCanvasFrameworkSDK. 4. Run the following command: `keytool -keystore keystore -alias jetty -genkey -keyalg RSA`. After you run this command, you’ll be prompted for the following information. Enter `123456` for the keystore password and `yes` to confirm at the end. When prompted, “Enter key password for \<jetty\>,” press Enter to use the keystore password. For the other information, you can enter values or leave them blank. ```nolang Enter keystore password: <Choose Your Password> Re-enter new password: <Choose Your Password> What is your first and last name? [Unknown]: <Enter First and Last Name> What is the name of your organizational unit? [Unknown]: <Enter an Org Unit> What is the name of your organization? [Unknown]: <Enter an Org> What is the name of your City or Locality? [Unknown]: <Enter a City> What is the name of your State or Province? [Unknown]: <Enter a State> What is the two-letter country code for this unit? [Unknown]: <Enter a Country> Is CN=XXXX, OU=XXXX, O=XXXX, L=XXXX, ST=XX, C=XX correct? [no]: yes Enter key password for <jetty> (RETURN if same as keystore password): ``` This creates a file named keystore in the directory c:\SalesforceCanvasFrameworkSDK. The keystore is used by Jetty for SSL support. 5. Run the Web server by entering this command: `target\bin\webapp.bat` (Windows) or `sh target/bin/webapp` (Unix/OS X). If you’re using Unix/OS X, you may need to add execute permissions to `webapp` before you can run it. Use this command to do so: `chmod +x target/bin/webapp`. 6. Verify that the app is running by opening a browser and navigating to the following URL: https://localhost:8443/examples/hello-world/index.jsp. Depending on your browser and security settings, you might need to add a security exception because you’re running a site with an unsigned SSL certificate. You should see a message that says, “This App must be invoked via a signed request!” This is an indication that the Web app is running locally. This message appears because the app is designed to receive a signed request from Salesforce, therefore, the app won’t run outside of the Salesforce canvas environment. **See Also** - [Quick Start—Advanced](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-intro.md) - [Clone the Project from GitHub](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-clone-the-project.md) - [Use a Connected App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-create-canvas-app.md) <!-- document id=a3b1a183e1ef0c0545cf06de1c344a77b11e90f9e5252f269fa595c99543279b url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-dollara-run.md --> # run() Deprecated. Use `getCallback()` instead. ## Signature `run (function func, String name)` ## Parameters **_func_:** Type: `function`. The function to run. **_name_:** Type: `String`. An optional name for the stack. <!-- document id=32b22838728c3ff89e7bf1e7080d33c9c9344e611f951a9cc3e8609023f87ce0 url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/forcemigrationtool-deploy-run-specific-tests.md --> # Running a Subset of Tests in a Deployment Test levels enable you to have more control over which tests are run in a deployment. To shorten deployment time to production, run a subset of tests when deploying Apex components. The default test execution behavior in production has also changed. By default, if no test level is specified, no tests are executed, unless your deployment package contains Apex classes or triggers. **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. If the code coverage of an Apex component in the deployment is less than 75%, the deployment fails. If one of the specified tests fails, the deployment also fails. We recommend that you test your deployment in sandbox first to ensure that the specified tests cover each component sufficiently. Even if your organization’s overall code coverage is 75% or more, the individual coverage of the Apex components being deployed can be less. If the code coverage requirement isn’t met, write more tests and include them in the deployment. To run a subset of tests, add the `testLevel="RunSpecifiedTests"` parameter to the deploy target. Specify each test class to run for a deploy target in a `<runTest> </runTest>` child element within the `sf:deploy` element. Add the test class name within the `<runTest> </runTest>` tags. Add as many `runTest` tags as you need, one for each test class. This deploy target example shows three test classes. Salesforce runs these test classes when deploying this package. ```xml <target name="deployCode"> <sf:deploy username="${sf.username}" password="${sf.password}" sessionId="${sf.sessionId}" serverurl="${sf.serverurl}" deployroot="codepkg" testLevel="RunSpecifiedTests"> <runTest>TestClass1</runTest> <runTest>TestClass2</runTest> <runTest>TestClass3</runTest> </sf:deploy> </target> ``` The test class name can include a namespace prefix. Add a namespace prefix if your organization has a namespace defined or if the test class belongs to a managed package. For example, if the namespace is `MyNamespace`, specify the test class as `MyNamespace.TestClass1`. If you don’t specify a test class to run in the target, the default deployment behavior applies when deploying to production. The default is all tests in your organization run on deployment except the tests that originate from installed managed packages. The default code coverage requirements are also enforced. The requirements are a minimum overall percentage of 75% for all classes and triggers, and no trigger can have 0% coverage. ## Notes About Running Specific Tests - You can specify only test classes. You can’t specify individual test methods. - We recommend that you refactor test classes to include the minimum number of tests that meet code coverage requirements. Refactoring your test classes can contribute to shorter test execution times, and as a result, shorter deployment times. - You can deactivate a trigger in the target organization by deploying it with an inactive state. However, the trigger must have been previously deployed with an active state. <!-- document id=5d84c8f011baad584beb7f10efcab632d7bdc4ddec04688d155051ce4fb2c005 url=/developer/current/en-us/platform/salesforce-migration-guide/guides/daas/meta-deploy-running-tests.md --> # Running Tests in a Deployment ## Default Test Execution in Production When no test level is specified in the deployment options, the default test execution behavior depends on the contents of your deployment package. When deploying to production, all tests, except those that originate from managed packages, are executed if your deployment package contains Apex classes or triggers. If your package doesn’t contain Apex components, no tests are run by default. In API version 33.0 and earlier, tests were run for components that required tests, such as custom objects, and not only for Apex components. For example, if your package contains a custom object, all tests are run in API version 33.0 and earlier. In contrast, starting with API version 34.0, no tests are run for this package. The API version corresponds to the version of your API client or the version of the tool you’re using (Ant Migration Tool). You can run tests for a deployment of non-Apex components. You can override the default test execution behavior by setting the test level in your deployment options. Test levels are enforced regardless of the types of components present in your deployment package. We recommend that you run all local tests in your development environment, such as sandbox, before deploying to production. Running tests in your development environment reduces the number of tests needed to run in a production deployment. ## Default Test Execution in Production for API Version 33.0 and Earlier For deployment to a production organization, all local tests in your organization are run by default. Tests that originate from installed managed packages aren’t run by default. If any test fails, the entire deployment is rolled back. If the deployment includes components for the following metadata types, all local tests are run. - ApexClass - ApexComponent - ApexPage - ApexTrigger - ArticleType - BaseSharingRule - CriteriaBasedSharingRule - CustomField - CustomObject - DataCategoryGroup - Flow - InstalledPackage - NamedFilter - OwnerSharingRule - PermissionSet - Profile - Queue - RecordType - RemoteSiteSetting - Role - SharingReason - Territory - Validation Rules - Workflow For example, no tests are run for the following deployments: - 1 CustomApplication component - 100 Report components and 40 Dashboard components But all local tests are run for any of the following example deployments, because they include at least one component from the list above: - 1 CustomField component - 1 ApexComponent component and 1 ApexClass component - 5 CustomField components and 1 ApexPage component - 100 Report components, 40 Dashboard components, and 1 CustomField component <!-- document id=f99d97ce55f248f21dbe06fc9ff97605aa5f0a7b61cbffb253d5b46ea27ae8fd url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-runtests.md --> # runTests() Run your Apex unit tests. ## Syntax ```java RunTestsResult[] = binding.runTests(RunTestsRequest request); ``` ## Usage To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, and send no emails. Such methods are flagged with the `@isTest` annotation in the method definition. Unit test methods must be defined in test classes, that is, classes annotated with `@isTest`. Use this call to run your Apex unit tests. This call supports the [DebuggingHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-debuggingheader.md) and the [SessionHeader](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-sessionheader.md). ## Sample Code—Java <!-- otherprops: java set_clipboard --> ```codesegment public void runTestsSample() { String sessionId = "sessionID goes here"; String url = "url goes here"; // Set the Apex stub with session ID received from logging in with the partner API _SessionHeader sh = new _SessionHeader(); apexBinding.setHeader( new ApexServiceLocator().getServiceName().getNamespaceURI(), "SessionHeader", sh); // Set the URL received from logging in with the partner API to the Apex stub apexBinding._setProperty(ApexBindingStub.ENDPOINT_ADDRESS_PROPERTY, url); // Set the debugging header _DebuggingHeader dh = new _DebuggingHeader(); dh.setDebugLevel(LogType.Profiling); apexBinding.setHeader( new ApexServiceLocator().getServiceName().getNamespaceURI(), "DebuggingHeader", dh); long start = System.currentTimeMillis(); RunTestsRequest rtr = new RunTestsRequest(); rtr.setAllTests(true); RunTestsResult res = null; try { res = apexBinding.runTests(rtr); } catch (RemoteException e) { System.out.println("An unexpected error occurred: " + e.getMessage()); } System.out.println("Number of tests: " + res.getNumTestsRun()); System.out.println("Number of failures: " + res.getNumFailures()); if (res.getNumFailures() > 0) { for (RunTestFailure rtf : res.getFailures()) { System.out.println("Failure: " + (rtf.getNamespace() == null ? "" : rtf.getNamespace() + ".") + rtf.getName() + "." + rtf.getMethodName() + ": " + rtf.getMessage() + "\n" + rtf.getStackTrace()); } } if (res.getCodeCoverage() != null) { for (CodeCoverageResult ccr : res.getCodeCoverage()) { System.out.println("Code coverage for " + ccr.getType() + (ccr.getNamespace() == null ? "" : ccr.getNamespace() + ".") + ccr.getName() + ": " + ccr.getNumLocationsNotCovered() + " locations not covered out of " + ccr.getNumLocations()); if (ccr.getNumLocationsNotCovered() > 0) { for (CodeLocation cl : ccr.getLocationsNotCovered()) System.out.println("\tLine " + cl.getLine()); } } } System.out.println("Finished in " + (System.currentTimeMillis() - start) + "ms"); } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`request`|[RunTestsRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-request.md)|A request that includes the Apex unit tests and the values for any fields that need to be set for this request.| ## Response [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) <!-- document id=535e3b5eb545269b5691f948bead9a3e79530a41065cc6f490713160ad273c40 url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-runtests-request.md --> # RunTestsRequest Specifies information about the Apex code to be tested. RunTestsRequest is part of [CompileAndTestRequest](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest-request.md), which is the request passed to the [`compileAndTest()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-compileandtest.md) call. This object is also passed to the Tooling SOAP API call `runTests()`. You can specify the same or different classes to be tested and compiled. Since triggers cannot be tested directly, they are not included in this object. Instead, you must specify a class that calls the trigger. If the request is sent to a production organization, this request is ignored and all unit tests defined for your organization are run. The RunTestsRequest object has the following properties: <sfdocstbl><table> <col> </col> <col> </col> <col> </col> <thead> <tr> <th> Name </th> <th> Type </th> <th> Description </th> </tr> </thead> <tbody> <tr> <td> <code>allTests</code> </td> <td> boolean </td> <td> If <code>allTests</code> is true, all unit tests defined for your organization are run. </td> </tr> <tr> <td> <code>classes</code> </td> <td> string[] </td> <td> An array of one or more objects. </td> </tr> <tr> <td> <code>namespace</code> </td> <td> string </td> <td> If specified, the namespace that contains the unit tests to be run. Do not use this property if you specify allTests as true. Also, if you execute <code>compileAndTest()</code> in a production organization, this property is ignored, and all unit tests defined for the organization are run. </td> </tr> <tr> <td> <code>maxFailedTests</code> </td> <td> int </td> <td> A mandatory parameter for the Tooling SOAP API call <code>runTests()</code> . To allow all tests in a run to execute, set <code>maxFailedTests</code> to <code>-1</code> . To stop the test run from executing new tests after a given number of tests fail, set <code>maxFailedTests</code> to an integer value from <code>0</code> to <code>1,000,000</code> . This integer value sets the maximum allowable test failures. A value of <code>0</code> causes the test run to stop if any failure occurs. A value of <code>1</code> causes the test run to stop on the second failure, and so on. </td> </tr> <tr> <td> <code>packages</code> </td> <td> string[] </td> <td> Do not use after version 10.0. For earlier, unsupported releases, the content of the package to be tested. </td> </tr> <tr> <td> <code>skipCodeCoverage</code> </td> <td> boolean </td> <td> Indicates whether to opt out of collecting code coverage information during Apex test runs. Available in API version 43.0 and later. </td> </tr> <tr> <td> <code>tests</code> </td> <td> <a href="#testsnode">TestsNode</a> [] </td> <td> <p> A mandatory parameter for the Tooling SOAP API call <code>runTests()</code> . Specifies individual test methods in an Apex test class. </p> <p> To specify classes or suites instead of a TestsNode[], set <code>tests</code> to <code>null</code> . </p> <p> Although this property accepts an array, the array can contain only one entry. </p> </td> </tr> </tbody> </table></sfdocstbl> ## TestsNode Specifies individual test methods in an Apex test class. |Name|Type|Description|Supported Methods| |----|----|-----------|-----------------| |`classId`|string|The ID of the Apex class that contains the test methods you want to run. `classId` or `className` is required.|Values are `getClassId()`, or `setClassId(new String "<your class ID>")`.| |`className`|string|The name of the Apex class that contains the test methods you want to run. To run tests from a managed package, include the package’s namespace using dot notation. `classId` or `className` is required.|Values are `getClassName()`, or `setClassName(new String "YourClassName")`.| |`testMethods`|string[]|The test methods you want to run. Required.|Values are `getTestMethods()`, or `setTestMethods(new String[] {"testMethod1", "testMethod2"}))`.| <!-- document id=21b2d45b560ad5c2b356628c58bf38286d2a6fd9578bcdb49dd6902649426706 url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-runtests-result.md --> # RunTestsResult Contains information about the execution of unit tests, including whether unit tests were completed successfully, code coverage results, and failures. A RunTestsResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`apexLogId`|string|The ID of an ApexLog object that is created at the end of a test run. The ApexLog object is created if there is an active trace flag on the user running an Apex test, or on a class or trigger being executed. This field is available in API version 35.0 and later.| |`codeCoverage`|[CodeCoverageResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)[]|An array of one or more CodeCoverageResult objects that contains the details of the code coverage for the specified unit tests.| |`codeCoverageWarnings`|[CodeCoverageWarning](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)[]|An array of one or more code coverage warnings for the test run. The results include both the total number of lines that could have been executed, as well as the number, line, and column positions of code that was not executed.| |`failures`|[RunTestFailure](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)[]|An array of one or more RunTestFailure objects that contain information about the unit test failures, if there are any.| |`flowCoverage`|FlowCoverageResult[]|An array of results from test runs that executed flows. This field is available in API version 44.0 and later.| |`flowCoverageWarnings`|FlowCoverageWarning[]|An array of warnings generated by test runs that executed flows. This field is available in API version 44.0 and later.| |`numFailures`|int|The number of failures for the unit tests.| |`numTestsRun`|int|The number of unit tests that were run.| |`successes`|[RunTestSuccess](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md)[]|An array of one or more RunTestSuccess objects that contain information about successes, if there are any.| |`totalTime`|double|The total cumulative time spent running tests, in milliseconds. This can be helpful for performance monitoring.| ## CodeCoverageResult The [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) object contains this object. It contains information about whether or not the compile of the specified Apex and run of the unit tests was successful. A CodeCoverageResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`dmlInfo`|CodeLocation[]|For each class or trigger tested, for each portion of code tested, this property contains the DML statement locations, the number of times the code was executed, and the total cumulative time spent in these calls. This can be helpful for performance monitoring.| |`id`|ID|The ID of the [CodeLocation](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md). The ID is unique within an organization.| |`locationsNotCovered`|CodeLocation[]|For each class or trigger tested, if any code is not covered, the line and column of the code not tested, and the number of times the code was executed.| |`methodInfo`|CodeLocation[]|For each class or trigger tested, the method invocation locations, the number of times the code was executed, and the total cumulative time spent in these calls. This can be helpful for performance monitoring.| |`name`|string|The name of the class or trigger covered.| |`namespace`|string|The namespace that contained the unit tests, if one is specified.| |`numLocations`|int|The total number of code locations.| |`numLocationsNotCovered`|int|The number of code locations not covered by any class or trigger.| |`soqlInfo`|CodeLocation[]|For each class or trigger tested, the location of SOQL statements in the code, the number of times this code was executed, and the total cumulative time spent in these calls. This can be helpful for performance monitoring.| |`soslInfo`|CodeLocation[]|For each class tested, the location of SOSL statements in the code, the number of times this code was executed, and the total cumulative time spent in these calls. This can be helpful for performance monitoring.| |`type`|string|Do not use. In early, unsupported releases, used to specify class or package.| ## CodeCoverageWarning The [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) object contains this object. It contains information about the Apex class which generated warnings. This object has the following properties: |Name|Type|Description| |----|----|-----------| |`id`|ID|The ID of the class which generated warnings.| |`message`|string|The message of the warning generated.| |`name`|string|The name of the class that generated a warning. If the warning applies to the overall code coverage, this value is null.| |`namespace`|string|The namespace that contains the class, if one was specified.| ## RunTestFailure The [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) object returns information about failures during the unit test run. This object has the following properties: |Name|Type|Description| |----|----|-----------| |`id`|ID|The ID of the class which generated failures.| |`message`|string|The failure message.| |`methodName`|string|The name of the method that failed.| |`name`|string|The name of the class that failed.| |`namespace`|string|The namespace that contained the class, if one was specified.| |`seeAllData`|boolean|Indicates whether the test method has access to organization data (`true`) or not (`false`). This field is available in API version 33.0 and later.| |`stackTrace`|string|The stack trace for the failure.| |`time`|double|The time spent running tests for this failed operation, in milliseconds. This can be helpful for performance monitoring.| |`type`|string|Do not use. In early, unsupported releases, used to specify class or package.| ## FlowCoverageResult This object contains information about the flow version and the number of elements executed by the test run. This object is available in API version 44.0 and later. |Name|Type|Description| |----|----|-----------| |`elementsNotCovered`|string|List of elements in the flow version that weren’t executed by the test run.| |`flowId`|string|The ID of the flow version. The ID is unique within an org.| |`flowName`|string|The name of the flow that was executed by the test run.| |`flowNamespace`|string|The namespace that contains the flow, if one is specified.| |`numElements`|int|The total number of elements in the flow version.| |`numElementsNotCovered`|int|The number of elements in the flow version that weren’t executed by the test run| |`processType`|FlowProcessType (enumeration of type string)|The process type of the flow version.| ## FlowCoverageWarning This object contains information about the flow version that generated warnings. This object is available in API version 44.0 and later. |Name|Type|Description| |----|----|-----------| |`flowId`|string|The ID of the flow version that generated the warning.| |`flowName`|string|The name of the flow that generated the warning. If the warning applies to the overall test coverage of flows within your org, this value is null.| |`flowNamespace`|string|The namespace that contains the flow, if one was specified.| |`message`|string|The message of the warning that was generated.| ## RunTestSuccess The [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) object returns information about successes during the unit test run. This object has the following properties: |Name|Type|Description| |----|----|-----------| |`id`|ID|The ID of the class which generated the success.| |`methodName`|string|The name of the method that succeeded.| |`name`|string|The name of the class that succeeded.| |`namespace`|string|The namespace that contained the class, if one was specified.| |`seeAllData`|boolean|Indicates whether the test method has access to organization data (`true`) or not (`false`). This field is available in API version 33.0 and later.| |`time`|double|The time spent running tests for this operation. This can be helpful for performance monitoring.| ## CodeLocation The [RunTestsResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-runtests-result.md) object contains this object in a number of fields. This object has the following properties: |Name|Type|Description| |----|----|-----------| |`column`|int|The column location of the Apex tested.| |`line`|int|The line location of the Apex tested.| |`numExecutions`|int|The number of times the Apex was executed in the test run.| |`time`|double|The total cumulative time spent at this location. This can be helpful for performance monitoring.| <!-- document id=244594626cc48a78a7c5dc0951be6170eca4ac53f16d486cc781c64d13f633a5 url=/developer/current/en-us/platform/aura-platform/guides/aura/components/components-config-for-flow-tips-runtime.md --> # Runtime Considerations for Flows That Include Aura Components Depending on where you run your flow, Aura components may look or behave differently than expected. The flow runtime app that's used for some distribution methods doesn't include all the necessary resources from the Lightning Component framework. When a flow is run from Flow Builder or a direct flow URL (https://yourDomain.my.salesforce.com/flow/MyFlowName), `force` and `lightning` events aren’t handled. To verify the behavior of your Aura components, test your flow in a way that handles `force` and `lightning` events, such as `force:showToast`. You can also add the appropriate event handlers directly to your component. |Distribution Method|Handles `force` and `lightning` Events| |-------------------|--------------------------------------| |Direct flow URL| | |Run and Debug buttons in Flow Builder| | |Run links on flow detail pages and list views| | |Web tab| | |Custom button or link| | |Lightning page|![Checkmark icon](https://developer.salesforce.com/media/shared/checkmark.png)| |Experience Builder site page|![Checkmark icon](https://developer.salesforce.com/media/shared/checkmark.png)| |Flow action|![Checkmark icon](https://developer.salesforce.com/media/shared/checkmark.png)| |Utility bar|![Checkmark icon](https://developer.salesforce.com/media/shared/checkmark.png)| |`flow:interview` Visualforce component| | |`lightning:flow` Aura component|Depends on where you embed the component or whether your component includes the appropriate event handlers| **See Also** - [*Component Library*: lightning:availableForFlowScreens Interface](https://developer.salesforce.com/docs/component-library/bundle/lightning:availableForFlowScreens/documentation) - [*Component Library*: lightning:availableForFlowActions Interface](https://developer.salesforce.com/docs/component-library/bundle/lightning:availableForFlowActions/documentation) - [Events Handled in the Salesforce Mobile App and Lightning Experience](https://developer.salesforce.com/docs/platform/aura-platform/events/events-one.md) <!-- document id=e68633d88a3c2be31616bbad31d9aa2bd430b6173246addb4c470eeefae2a04e url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-high-velocity-sales.md --> # Sales Engagement Actions Manage your Sales Engagement cadences using invocable actions. Sales Engagement must be set up in your org. The user must have permissions to use cadences. ## Supported REST HTTP Methods **URIs:** - [Assign Target To Cadence](#assign-target-to-cadence): `/services/data/vXX.X/actions/standard/assignTargetToSalesCadence` - [Remove Target From Cadence](#remove-target-from-cadence): `/services/data/vXX.X/actions/standard/removeTargetFromSalesCadence` - [Pause Cadence Tracker](#pause-cadence-tracker): `/services/data/vXX.X/actions/standard/pauseSalesCadenceTracker` - [Resume Cadence Tracker](#resume-cadence-tracker): `/services/data/vXX.X/actions/standard/resumeSalesCadenceTracker` - [Change Cadence Target Assignee](#change-cadence-target-assignee): `/services/data/vXX.X/actions/standard/changeSalesCadenceTargetAssignee` - [Modify Cadence Tracker Attributes](#modify-cadence-tracker-attributes): `/services/data/vXX.X/actions/standard/modifyCadenceTrackerAttributes` - [Send Cadence Event](#send-cadence-event): `/services/data/vXX.X/actions/standard/sendSalesCadenceEvent` - [Select Template For Cadence Step Tracker](#select-template-for-cadence-step-tracker): `/services/data/vXX.X/actions/standard/selectTemplateForSalesCadenceStepTracker` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` **Other Information:** [Error Response Types](#error-response-types) ## Assign Target to Cadence Available in API version 45.0. URI: `/services/data/vXX.X/actions/standard/assignTargetToSalesCadence` |Input|Type|Description| |-----|----|-----------| |`salesCadenceNameOrId`|string|Required. The name or ID of the cadence.| |`startStepNameOrId`|string|The name or ID of the cadence step where the target starts in the cadence.| |`targetId`|ID|Required. The ID of the contact, a lead, or person account to add to the cadence.| |`userId`|ID|The ID of the user designated as the target assignee. The target assignee is the sales rep who performs the cadence steps for the target.| |`relatedToId`|ID|The ID of the target's related opportunity or invoice. This field is only available when Relate Opportunities to Cadences or Use Cadences for Collections is turned on in Sales Engagement Setup.| **Sample Input** The following code sample adds a target to a cadence: ```apex { "inputs" : [ { "salesCadenceNameOrId" : "77Cxx0000004CXEEA2", "targetId" : "00Qxx000002TRI2EAO" }] } ``` ## Remove Target from Cadence Available in API version 45.0. URI: `/services/data/vXX.X/actions/standard/removeTargetFromSalesCadence` |Input|Type|Description| |-----|----|-----------| |`targetId`|ID|Required if `actionCadenceTrackerId` is null. The ID of the contact, a lead, or person account to remove from the cadence.| |`actionCadenceTrackerId`|ID|Required if `targetId` is null. The ID of the action cadence tracker to remove from the cadence.| |`completionReasonCode`|string|Required. The completion reason code indicates how the target competed the cadence. The only valid value is `ManuallyRemoved`.| |`completionDisposition`|string|The disposition of the completed cadence tracker. Valid values are: `Success`, `Customer Engaged`, `Customer Connected`, `Contact Later`, `No Response`, `Not Interested`, `Disqualified`, `Bad Data`, or `Duplicate`.| |`relatedToId`|ID|The ID of the target's related opportunity or invoice. This field is only available when Relate Opportunities to Cadences or Use Cadences for Collections is turned on in Sales Engagement Setup.| |`relatedToAttributionType`|string|The attribution type of the target's related opportunity or invoice. This field is only available when Relate Opportunities to Cadences or Use Cadences for Collections is turned on in Sales Engagement Setup. Valid values are: `Activation` (valid for both opportunities and invoices), `Maturation` (valid for opportunities), or `Collected` (valid for invoices).| |`shouldApplyUserContext`|boolean|Indicates whether to remove only action cadence trackers owned by the running user (`true`) or not (`false`).| **Sample Input** The following code sample removes a target from a cadence: ```apex { "inputs" : [ { "completionReasonCode" : "ManuallyRemoved", "targetId" : "00Qxx000002TRI2EAO" }] } ``` ## Pause Cadence Tracker Pause a target in its cadence. Available in API version 50.0. URI: `/services/data/vXX.X/actions/standard/pauseSalesCadenceTracker` |Input|Type|Description| |-----|----|-----------| |`targetId`|ID|Required. The ID of the contact, a lead, or person account to pause.| |`resumeTime`|String|Optional. The scheduled end time for the pause.| **Sample Input** The following code sample pauses a target in its cadence: ```apex { "inputs" : [ { "targetId" : "00Qxx000002TRI2EAO", "resumeTime" : "2021-06-15T05:30:00:521917Z" }] } ``` ## Resume Cadence Tracker Resume a target in its cadence. Available in API version 50.0. URI: `/services/data/vXX.X/actions/standard/resumeSalesCadenceTracker` |Input|Type|Description| |-----|----|-----------| |`targetId`|ID|Required. The ID of the contact, a lead, or person account to pause.| **Sample Input** The following code sample resumes a target in its cadence: ```apex { "inputs" : [ { "targetId" : "00Qxx000002TRI2EAO" }] } ``` ## Change Cadence Target Assignee Available in API version 50.0. URI: `/services/data/vXX.X/actions/standard/changeSalesCadenceTargetAssignee` |Input|Type|Description| |-----|----|-----------| |`targetId`|ID|Required. The ID of the contact, a lead, or person account to pause.| |`userId`|ID|The ID of the user designated as the target assignee. The target assignee is the sales rep who performs the cadence steps for the target.| **Sample Input** The following code changes a target's assignee: ```apex { "inputs" : [ { "targetId" : "00Qxx000002TRI2EAO", "userId" : "005R0000000eg3zIAA", }] } ``` ## Modify Cadence Tracker Attributes Available in API version 51.0. URI: `/services/data/vXX.X/actions/standard/modifyCadenceTrackerAttributes` |Input|Type|Description| |-----|----|-----------| |`actionCadenceTrackerId`|ID|Required. The ID of the cadence tracker to modify.| |`completionDisposition`|string|The disposition of the completed cadence tracker. Valid values are: `Success`, `Customer Engaged`, `Customer Connected`, `Contact Later`, `No Response`, `Not Interested`, `Disqualified`, `Bad Data`, or `Duplicate`.| |`relatedToId`|ID|The ID of the target's related opportunity or invoice. This field is only available when Relate Opportunities to Cadences or Use Cadences for Collections is turned on in Sales Engagement Setup.| |`relatedToAttributionType`|string|The attribution type of the target's related opportunity or invoice. This field is only available when Relate Opportunities to Cadences or Use Cadences for Collections is turned on in Sales Engagement Setup. Valid values are: `Activation` (valid for both opportunities and invoices), `Maturation` (valid for opportunities), or `Collected` (valid for invoices).| **Sample Input** The following code modifies a cadence tracker with a Completion Disposition of "Customer Engaged", a related opportunity, and an Attribution Type of "Activation": ```apex { "inputs" : [ { "actionCadenceTrackerId" : "0qBR00000005CXvMAM", "completionDisposition" : "Customer Engaged", "relatedToId" : "006R0000003DNpJIAW", "relatedToAttributionType" : "Activation" }] } ``` ## Send Cadence Event Available in API version 52.0. Send an event to a cadence, such as skipping or manually completing a step. URI: `/services/data/vXX.X/actions/standard/sendSalesCadenceEvent` |Input|Type|Description| |-----|----|-----------| |`recordId`|ID|Required. The ID of the cadence step tracker to send the event to.| |`eventType`|string|Required. The type of event to send. Valid values are: `Skip` or `ManualComplete`.| **Sample Input** The following code sends a Manual Complete event to a cadence step tracker: ```apex { "inputs" : [ { "recordId" : "8HFR00000005WyqOAE", "eventType" : "Manual Complete" }] } ``` ## Select Template for Cadence Step Tracker Retrieve the email template or call script from a cadence step or cadence step variant (if variant testing) to be used while executing a step for a particular target. Available in API version 53.0. URI: `/services/data/vXX.X/actions/standard/selectTemplateForSalesCadenceStepTracker` |Input|Type|Description| |-----|----|-----------| |`stepTrackerId`|ID|Required. The ID of the cadence step tracker.| |Output|Type|Description| |------|----|-----------| |`output`|JSON|The email template or call script ID and its related split percentage.| |`error`|string|The error message returned when the action fails.| **Sample Input** The following code retrieves the email template or call script for two cadence steps: ```apex {"inputs": [ { "stepTrackerId" : "8HFR00000006LE8OAM" }, { "stepTrackerId" : "8HFR00000006LEDOA2" }] } ``` **Sample Output** The following code sample illustrates a response after one success and one failure. ```apex [ { "actionName" : "selectTemplateForSalesCadenceStepTracker", "errors" : null, "isSuccess" : true, "outputValues" : { "output" : { "SplitPercentage" : 10.0, "TemplateId" : "00XR0000000UOtZMAW" } } }, { "actionName" : "selectTemplateForSalesCadenceStepTracker", "errors" : [ { "statusCode" : "UNKNOWN_EXCEPTION", "message" : "No template was found.", "fields" : [ ] } ], "isSuccess" : false, "outputValues" : { "error" : "No template was found." } } ] ``` ## Error Response Types Sales Engagement actions can respond with success or errors. If any type of error occurs with an action, the `isSuccess` field is `false`. This example illustrates a success response for the Assign Target To Cadence action. ```apex [ { "actionName" : "assignTargetToSalesCadence", "isSuccess" : true } ] ``` This example illustrates an error caused by sending invalid input values to the Assign Target To Cadence action. ```apex [ { "actionName" : "assignTargetToSalesCadence", "errors" : [ { "statusCode" : "UNKNOWN_EXCEPTION", "message" : "The object needs to be a valid cadence entity.", "fields" : [ ] } ], "isSuccess" : false, "outputValues" : { "error" : "The object needs to be a valid cadence entity." } } ] ``` <!-- document id=1a5b71d7ac475793e3a7c4bcf2d2d5e56411b9ced555f3f049e33d1c32f05b13 url=/developer/current/en-us/platform/salesforce-app-limits-cheatsheet/guides/salesforce-app-limits-cheatsheet-pdf-archive.md --> # Salesforce App Limits Quick Reference Previous PDF Versions | API Version | Release | PDF | | ----------- | ---------- | ------------------------------------------------------------------------------------------------------------------------ | | 68.0 | Winter '27 | [Download PDF](https://resources.docs.salesforce.com/264/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf) | <!-- document id=433b403d8c5d87bf357b2d5cc629794560217dcefc7c1ed99e03ae294b4a5024 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-salesforce1-app-access-considerations.md --> # Salesforce Mobile App Access Considerations Keep these considerations in mind when modifying a canvas app that appears in the Salesforce mobile app. By necessity, the Salesforce mobile app layout is different than the full Salesforce site layout that you’re used to. Remember the following when creating a canvas app for use in the Salesforce mobile app. - Because canvas apps are designed to display your third-party application inside of Salesforce, the device must have access to your canvas app URL. If your app is only accessible behind a firewall, the mobile device must be behind the firewall, too. If users don’t have access to the canvas URL, they receive an error—possibly a 404 or 500 error. - When accessing your canvas app as an action, if the canvas app uses the “What are you working on” header, the header is fixed at the top of the page and your canvas app scroll area falls below the header text box. - The canvas app link and description in the feed might display fewer characters than what is displayed in the full Salesforce site. - Depending on the device you use, the feed screen can change if the device is rotated. Your canvas app should support rotation if possible. Use the orientation event to handle changes in device orientation. - The heights used in the Salesforce mobile app and the full Salesforce site are different. Use the Dimensions object in the signed request to render your actions correctly in the publisher. - In the action menu, long action labels might be truncated. - The feed layout is different than that of the full Salesforce site. Instead of an app opening in the feed, a page opens that displays the canvas app on the entire screen. To return to the Salesforce mobile app, tap ![The back arrow.](https://developer.salesforce.com/media/canvas-framework/sfdc1_back_arrow.png). - When you view the action bar or Feed, the default Canvas puzzle icon displays for canvas apps. You can override this default action icon with an image you provide. - When a canvas app appears as an option in the navigation menu, the default Canvas puzzle icon is used. You can customize the icon in the connected app settings of your canvas app. - Canvas apps aren’t available when the user accesses Salesforce offline. **See Also** - [Canvas in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-in-salesforce1.md) - [Salesforce Mobile App Context Considerations](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-salesforce1-context-considerations.md) - [Salesforce Mobile App Custom Icons](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-salesforce1-icon-considerations.md) - [Dimensions](https://developer.salesforce.com/docs/platform/reference/dimensions-object.md) - [Handling Orientation Changes in Your Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/resizing/canvas-app-orientation-code-example.md) - [Alternatives to Cookies for User Tracking](https://developer.salesforce.com/docs/platform/canvas-framework/canvas-app-iframe-considerations.md) <!-- document id=9bd74025f9360ee8e5a9e0a64631b20a1d0738b32db2d1cac972d3ddf677f8a2 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-salesforce1-context-considerations.md --> # Salesforce Mobile App Context Considerations Keep these considerations in mind when you display a canvas app inside of the Salesforce mobile app. When you display a canvas app inside of the feed or publisher, the canvas context you receive (either from the Signed Request or from the `getContext` call) contains information specific to the Salesforce mobile app publisher. - You can verify you’re on either the feed or publisher by looking at the `displayLocation` value in the environment section. For publisher, `displayLocation` is set to `Publisher`. For the feed, `displayLocation` is set to `ChatterFeed`. - When creating a Canvas feed item, you can specify a `JSON` string as the parameter’s value. When the context is sent, any value in the parameter’s field on the feed item is sent in the parameters of the environment section of the context. - As with any canvas app, the context contains information about the app’s dimensions. Since Salesforce is designed for mobile, the sizes we provide for it are different than the ones we provide for the full Salesforce sites. - To create a single-finger touch scrolling experience: - Ensure that the outermost `div` elements contain the following properties. - min-height: 250px; - overflow: scroll; - width: 100%; - -webkit-overflow-scrolling: touch; - -webkit-transform: translated(0%,0px,0px); - Set the `height` attribute to the `clientHeight` value delivered in the signed request. For example: ```nolang // Where sr is a parsed signed request object. var h = parseInt(sr.context.environment.dimensions.clientHeight, 10); Sfdc.canvas.byId('divElementId').style.height = h; ``` - The `clientHeight` value can be very small, particularly in a phone’s landscape mode, and users might not be able to see any content. Use `min-height` set to the desired height in pixels to ensure a good user experience. - In the navigation menu, the default puzzle icon size is 60 pixels by 60 pixels. **See Also** - [Canvas in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-in-salesforce1.md) - [Salesforce Mobile App Access Considerations](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-salesforce1-app-access-considerations.md) - [Resizing a Canvas App](https://developer.salesforce.com/docs/platform/canvas-framework/resizing/canvas-app-resizing.md) - [Salesforce Mobile App Custom Icons](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-salesforce1-icon-considerations.md) <!-- document id=022c48b7adc127ce9be1776010de81a48196b18f716262b58f07ba7290e9d235 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-salesforce1-icon-considerations.md --> # Salesforce Mobile App Custom Icons Custom icons help distinguish your app in the Salesforce mobile app. If you don’t customize the icon for your app, you’ll get the default puzzle-piece icon. You can customize the icon that is used in the Salesforce navigation menu. You set this icon in the Icon URL entry in the Basic Information section of the connected app settings for your canvas app. From Setup, enter `Apps` in the Quick Find box, then select **Apps** and click **Edit** for your connected app. The icon URL must be a secure HTTPS URL that points to an icon image file. The image file must be in the GIF, JPG, or PNG file format. For the Salesforce navigation menu, the icon cannot be larger than 60 pixels high by 60 pixels wide. The custom icon that is used in the Salesforce navigation menu is also used in the Chatter tab and the Canvas App Previewer. If your canvas app will be shown in the navigation menu, we recommend that you use a 60x60 pixel size icon and let Salesforce automatically resize the icon to the smaller size that is needed for the Chatter tab and the Canvas App Previewer. You can also customize the icon that is used in the Salesforce action bar and action menu for a canvas app. The action bar uses the custom icon set for the action that accesses the canvas app, not the custom icon that is associated with the connected app. You set the action icons by uploading a static resource file for your custom icon and then using this static resource as the icon for the global action. The static resource icon file should be in the PNG format, with a size of 120 pixels high by 120 pixels wide. See “Custom Icon Guidelines and Best Practices” in the [Salesforce Mobile App Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.salesforce1.meta/salesforce1/salesforce1_guide_introduction.htm) for more guidelines on custom action icons. **See Also** - [Canvas in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-in-salesforce1.md) - [Salesforce Mobile App Context Considerations](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-salesforce1-context-considerations.md) <!-- document id=1804af2dfb0020006fdcd775f86db2ef838dba38afbb6c124f9ca7d1a55d8909 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-salesforce1-navigation-methods.md --> # Salesforce Mobile App Navigation Methods for Use with Canvas Apps The Canvas framework includes methods that you can use to smoothly integrate navigation between a canvas app and the Salesforce mobile app, without needing to use Visualforce. To circumvent the navigational limitations of the iframe that contains a canvas app, use Canvas methods. These methods offer a simpler alternative to Visualforce pages for controlling navigation to or from canvas apps in the Salesforce app. For example, your canvas app code can call Salesforce "create record" logic to navigate to the page where the **Create Account** button resides. Clicking the button triggers a navigation method to go to the record creation page, which is outside of the canvas app. These methods within the Canvas framework are events that reside in the JavaScript library. When you call one of the navigation methods from your canvas code, you send an event into Salesforce that reads the payload and directs the user to the specified destination. Calling the methods from your canvas app is slightly different than calling functions from a Visualforce page, because the methods are proxied to the Salesforce container through the Canvas cross-domain API. Reference the navigation method as an event variable, with name and payload. For example: `var event = {name:"s1.createRecord", payload: {entityName: "Account", recordTypeId: "00h300000001234"}};` ## s1.back **Payload:** `{"refresh" : true}` Navigates to the previous state that's saved in the `sforce.one` history. It's equivalent to clicking a browser's Back button. `refresh` is optional. By default, the page doesn't refresh. Pass `true` to refresh the page if possible. ## s1.navigateToSObject **Payload:** `{"recordId" : "001XXXXXXXXXXXX", "view" : "chatter"}` Navigates to an sObject record, specified by a 15-character or 18-character `recordId`. This record "home" has several views, which in the Salesforce app are available as slides that the user can swipe between. Record IDs corresponding to ContentNote SObjects aren't supported. `view` is optional and defaults to `detail`; it specifies the slide within record home to display initially. Possible values are `detail` (the record detail slide), `chatter` (the Chatter slide), or `related` (the related slide). ## s1.navigateToURL **Payload:** `{"url" : "https://salesforce.com/apex/v.apexp", "isredirect" : true}` Navigates to the specified URL. Relative and absolute URLs are supported. Relative URLs are relative to the Lightning domain, and retain navigation history. External URLs—that is, URLs that are outside the Lightning domain—open in a separate browser window. URLs corresponding to ContentNote SObjects aren't supported. Use relative URLs to navigate to different screens within your app. Use external URLs to allow the user to access a different site or app, where those actions don't need to be preserved in your app. To return the user to your app, the separate window that's opened by an external URL must be closed when the user is finished with the other app. The new window has a separate history from your app, and this history is discarded when the window is closed. Discarding the history of a new window prevents the user from clicking a Back button to go back to your app; the user must close the new window. Depending on the user's device platform, device settings, version of Salesforce, and authentication requirements for the external URL being opened, the separate browser window might require authentication or reauthentication. `mailto:`, `tel:`, `geo:`, and other URL schemes are supported for launching external apps and attempt to "do the right thing." However, support varies by mobile platform and device. `mailto:` and `tel:` are reliable, but we recommend that you test any other URLs on a range of expected devices. `isredirect` is optional and defaults to `false`. Set it to `true` to indicate that the new URL should replace the current one in the navigation history. Be careful when using `navigateToURL` within the `onClick` handler of an `<apex:commandButton>` or any `<button type="submit">` or `<input type="submit">`. Even if `isredirect=true`, the default click action of the command button is a form post. In this scenario, the command button performs a form post and a `navigateToURL` action, requiring the user to click the back button twice to navigate to the previous page. To prevent the default click action, configure the `onClick` handler to either call `event.preventDefault()` or return `false`. ## s1.navigateToFeed **Payload:** `{"subjectId" : "001XXXXXXXXXXXX", "type" : "NEWS"}` Navigates to the feed of the specified `type`, scoped to the `subjectId`. For some feed `type`s, the `subjectId` is required but ignored. For those feed `type`s, pass the current user's ID as the `subjectId`. Possible values for `type`: - `BOOKMARKS`: Contains all feed items saved as bookmarks by the context user. Pass the current user's ID as the `subjectId`. - `COMPANY`: Contains all feed items except feed items of type `TrackedChange`. To see the feed item, the user must have sharing access to its parent. Pass the current user's ID as the `subjectId`. - `FILES`: Contains all feed items that contain files posted by people or groups that the context user follows. Pass the current user's ID as the `subjectId`. - `GROUPS`: Contains all feed items from all groups the context user either owns or is a member of. Pass the current user's ID as the `subjectId`. - `NEWS`: Contains all updates for people the context user follows, groups the user is a member of, and files and records the user is following. Contains all updates for records whose parent is the context user. Pass the current user's ID as the `subjectId`. - `PEOPLE`: Contains all feed items posted by all people the context user follows. Pass the current user's ID as the `subjectId`. - `RECORD`: Contains all feed items whose parent is a specified record, which could be a group, user, object, file, or any other standard or custom object. When the record is a group, the feed also contains feed items that mention the group. When the record is a user, the feed contains only feed items on that user. You can get another user's record feed. Pass the record's ID as the `subjectId`. - `TO`: Contains all feed items with mentions of the context user. Contains feed items the context user commented on and feed items created by the context user that are commented on. Pass the current user's ID as the `subjectId`. - `TOPICS`: Contains all feed items that include the specified topic. Pass the topic's ID as the `subjectId`. This value is supported in Salesforce for mobile web only. Topics aren't available in Salesforce for iOS or Salesforce for Android. ## s1.navigateToFeedItemDetail **Payload:** `{"feedItemId" : "001XXXXXXXXXXXX"}` Navigates to the specific feed item, `feedItemId`, and any associated comments. ## s1.navigateToRelatedList **Payload:** `{"relatedListId" : "001XXXXXXXXXXXX", "parentRecordId" : "001XXXXXXXXXXXX"}` Navigates to a related list for the `parentRecordId`. For example, to display a related list for a Warehouse object, the `parentRecordId` is `Warehouse__c.Id`. `relatedListId` is the API name or ID of the related list to display. ## s1.navigateToList **Payload:** `{"listViewId" : "001XXXXXXXXXXXX", "listViewName" : "myListView", "scope" : "scope"}` Navigates to the list view that's specified by the `listViewId`, which is the ID of the list view to be displayed. `listViewName` sets the title for the list view; it doesn't need to match the actual name that's saved for the list view. To use the saved name, set `listViewName` to null. Set `scope` to the name of the sObject in the view, for example, "Account" or "MyObject__c". ## s1.createRecord **Payload:** `{"entityName" : "MyObject__c", "recordTypeId" : "001XXXXXXXXXXXX"}` Opens the page to create a record for the specified `entityName`, for example, "Account" or "MyObject__c". `recordTypeId` is optional and specifies the record type for the created object. Calling `createRecord` without providing a `recordTypeId` may result in an error. ## s1.editRecord **Payload:** `{"recordId" : "001XXXXXXXXXXXX"}` Opens the page to edit the record specified by `recordId`. For information about navigation methods for use with Visualforce, see the Salesforce Mobile App Developer's Guide. **See Also** - [Visualforce Considerations](https://developer.salesforce.com/docs/platform/canvas-framework/canvas-app-vf-considerations.md) - [Canvas in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-in-salesforce1.md) <!-- document id=d884b42d2221924c14eedef948298bfdf3e228d02ba7d436f9720bf8ca5c74a5 url=/developer/current/en-us/platform/mobile-push-notifications/guides/mobile-push-notifications-pdf-archive.md --> # Salesforce Mobile Notifications Implementation 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/salesforce_mobile_push_notifications_implementation.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_mobile_push_notifications_implementation.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/salesforce_mobile_push_notifications_implementation.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/salesforce_mobile_push_notifications_implementation.pdf) | <!-- document id=2e74a6e0da0db7f2ccdc85122e3a37c0f7feafbea5a6c7d73d239879376226a3 url=/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-soql.md --> # Salesforce Object Query Language (SOQL) Use the Salesforce Object Query Language (SOQL) to search your organization’s Salesforce data for specific information. SOQL is similar to the SELECT statement in the widely used Structured Query Language (SQL) but is designed specifically for Salesforce data. With SOQL, you can construct simple but powerful query strings in several environments. - Using the `queryString` parameter of a SOAP API query() call. See [query()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_query.htm) in the _SOAP API Developer Guide_. - Using the `q` parameter of a REST API query request. See [Query](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_query.htm) in the _REST API Developer Guide_. - Using Apex statements. See [SOQL and SOSL Queries](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL.htm) in the _Apex Developer Guide_. - Using Visualforce controllers and getter methods. See [Controller Methods](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_methods.htm) in the _Visualforce Developer Guide_. - Using the Salesforce CLI. See [force:data:soql:query](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_force_data.htm#cli_reference_force_data_soql_query) in the data Commands topic of the _Salesforce CLI Command Reference_. - Using an extension for Visual Studio Code. See [Write SOQL Queries](https://developer.salesforce.com/tools/vscode/en/soql/writing) in _Salesforce Extensions for Visual Studio Code_. Similar to the SELECT command in Structured Query Language (SQL), SOQL allows you to specify the source object (such as Account), a list of fields to retrieve, and conditions for selecting rows in the source object. **note:** SOQL doesn’t support all advanced features of the SQL SELECT command. For example, you can’t use SOQL to perform arbitrary join operations, use wildcards in field lists, or use calculation expressions. SOQL uses the SELECT statement combined with filtering statements to return sets of data, which can optionally be ordered: ```soql SELECT one or more fields FROM an object WHERE filter statements and, optionally, results are ordered ``` For example, the following SOQL query returns the value of the `Id` and `Name` field for all Account records if the value of `Name` is `Sandy`: <!-- otherprops: soql --> ```codesegment SELECT Id, Name FROM Account WHERE Name = 'Sandy' ``` **note:** Apex requires that you surround SOQL and SOSL statements with square brackets to use them in your statements. You can use Apex script variables and expressions when preceded by a colon (`:`). For a complete description of the syntax, see [SOQL SELECT Syntax](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select.md). ## When to Use SOQL Use SOSL when you don’t know which object or field the data resides in, and you want to: - Retrieve data for a specific term that you know exists within a field. Because SOSL can tokenize multiple terms within a field and build a search index from this, SOSL searches are faster and can return more relevant results. - Retrieve multiple objects and fields efficiently where the objects might or might not be related to one another. - Retrieve data for a particular division in an organization using the divisions feature. - Retrieve data that’s in Chinese, Japanese, Korean, or Thai. Morphological tokenization for CJKT terms helps ensure accurate results. **note:** With archived data and big objects, you can use only some SOQL features. For more information, see [SOQL with Big Objects](https://developer.salesforce.com/docs/atlas.en-us.bigobjects.meta/bigobjects/big_object_querying.htm). **See Also** - [_Salesforce Developer Limits and Allocations Quick Reference_: SOQL and SOSL Limits for Search Queries](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm) <!-- document id=3eebd0640f67bf680dafbe1030f50ed10d17ddd6aef2065c79bd5f969444defd url=/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-sosl.md --> # Salesforce Object Search Language (SOSL) Use the Salesforce Object Search Language (SOSL) to construct text-based search queries against the search index. When building efficient SOSL queries, create filters that are selective. Search analyzes all records in the index and by default, only the top 2,000 matched records are returned based on relevancy. This API supports pagination to fetch additional matches. Sharing is applied after the result set is returned from the search stack. If your filters aren’t selective and cause search term matches of more than 2000 records, there’s a possibility of running into search crowding. You can search text, email, and phone fields for multiple objects, including custom objects, that you have access to in a single query in the following environments. - SOAP API search() calls. See [search()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_search.htm) in the _SOAP API Developer Guide_. - REST API Search calls. See [Search](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_search.htm) in the _REST API Developer Guide_. - Apex statements. See [SOQL and SOSL Queries](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL.htm) in the _Apex Developer Guide_. - Visualforce controllers and getter methods. See [Controller Methods](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_methods.htm) in the _Visualforce Developer Guide_. - Schema Explorer of the Eclipse Toolkit. See [Schema Explorer](https://developer.salesforce.com/docs/atlas.en-us.eclipse.meta/eclipse/eclipse_schema_browser.htm) in the _Force.com IDE Developer Guide_. **note:** If your org has relationship queries enabled, SOSL supports SOQL relationship queries. ## When to Use SOSL Use SOSL when you don’t know which object or field the data resides in, and you want to: - Retrieve data for a specific term that you know exists within a field. Because SOSL can tokenize multiple terms within a field and build a search index from this, SOSL searches are faster and can return more relevant results. - Retrieve multiple objects and fields efficiently where the objects might or might not be related to one another. - Retrieve data for a particular division in an organization using the divisions feature. - Retrieve data that’s in Chinese, Japanese, Korean, or Thai. Morphological tokenization for CJKT terms helps ensure accurate results. ## Performance Considerations If your searches are too general, they’re slow and return too many results. Use the following clauses to define efficient text searches. - `IN`: Limits the types of fields to search, including email, name, or phone. - `LIMIT`: Specifies the maximum number of rows to return. - `OFFSET`: Displays the search results on multiple pages. - `RETURNING`: Limits the objects and fields to return. - `WITH DATA CATEGORY`: Specifies the data categories to return. - `WITH DivisionFilter`: Specifies the division field to return. - `WITH NETWORK`: Specifies the Experience Cloud site ID to return. - `WITH PricebookId`: Specifies the price book ID to return. ## Navigating This Document - To see a list of available resources, see [SOSL Syntax](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-syntax.md#sosl-syntax). - To get started working with SOSL, see [Example Text Searches](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-examples.md#example-text-searches). <!-- document id=5b590a60bbbb69f98a9ece81443f09768d0053bf71b739b28a6845f050939179 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-omnichannel-inventory.md --> # Salesforce Omnichannel Inventory Actions Manage inventory availability and provide omnichannel commerce experiences in flows with Salesforce Omnichannel Inventory. For more information about using Omnichannel Inventory actions in flows, see [Salesforce Omnichannel Inventory Flow Core Actions](https://help.salesforce.com/HTViewHelpDoc?id=flow_ref_elements_oci_actions_list.htm) in Salesforce Help. These actions are available in API version 51.0 and later. Your org must have Salesforce Omnichannel Inventory enabled. ## Supported REST HTTP Methods **URI:** Get a specific Omnichannel Inventory action: `/services/data/vXX.X/actions/standard/oci_action_name` **Formats:** JSON, XML **HTTP Methods:** GET **Authentication:** `Authorization: Bearer token` **Notes:** You can also call the corresponding Connect REST API endpoints or Apex ConnectApi methods. For more information, see [Omnichannel Inventory Resources](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_omnichannel_inventory_resources.htm) in the *Connect REST API Developer Guide* and [ConnectApi Namespace](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_connect_api.htm) in the *Apex Developer Guide*. In flows, Omnichannel Inventory action inputs and outputs use Apex-defined variables that map to input and output classes in the ConnectApi namespace. <!-- document id=4731ae3882c13c19147adf85a215e132ede9e9b7d467f0799fac85e31f06f0a8 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-order-management.md --> # Salesforce Order Management Actions Manage, fulfill, and service orders in flows with Salesforce Order Management. For more information about using Order Management actions in flows, see [Salesforce Order Management Flow Core Actions](https://help.salesforce.com/HTViewHelpDoc?id=flow_ref_elements_om_actions_list.htm) in Salesforce Help. These actions are available in API version 48.0 and later. Your org must have a Salesforce Order Management license. ## Supported REST HTTP Methods **URI:** Get a specific Order Management action: `/services/data/vXX.X/actions/standard/om_action_name` **Formats:** JSON, XML **HTTP Methods:** GET **Authentication:** `Authorization: Bearer token` **Notes:** You can also call the corresponding Connect REST API endpoints or Apex ConnectApi methods. For more information, see [Order Management Resources](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_order_management_resources.htm) in the *Connect REST API Developer Guide* and [ConnectApi Namespace](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_connect_api.htm) in the *Apex Developer Guide*. In flows, Order Management action inputs and outputs use Apex-defined variables that map to input and output classes in the ConnectApi namespace. <!-- document id=6dfdf5238f9c8b07bfeab931aa3ed323e109bbe50cf58416dd224017e6ba76dd url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/mobile/pages-mobile-platform-dev-process-intro.md --> # Salesforce Platform Development Process The processes used for developing in Lightning Experience and the Salesforce mobile app are the same. If you’re used to developing for Salesforce Classic, the development process for Lightning Experience and the Salesforce mobile app has a few differences, but much of it will be familiar to you. When creating Visualforce pages for the Salesforce mobile app, it’s important that you set up your tools and testing environments correctly. In this section, we will go over the best practices for the Salesforce mobile platform development process. - **[Setting Up Your Development System](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-mobile-platform-dev-process-system.md)** Salesforce provides several different tools and ways to write, edit, and view your code. - **[The Development Process and the Importance of Testing](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-mobile-platform-dev-process-importance-testing.md)** It’s important to test your Visualforce pages before deploying them in production. Test your pages across different environments, devices, and users. - **[Testing Visualforce Pages in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-mobile-platform-dev-process-testing-salesforce1.md)** If you’re creating pages that will be used in Lightning Experience, Salesforce Classic, and the Salesforce mobile app, review your pages in all environments while you’re working on them. To test thoroughly, use multiple browsers, or even multiple devices, to view your pages. You’ll want to have access to at least one additional test user as well. - **[Understanding the Salesforce Mobile App Container](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-mobile-salesforce1-container.md)** In Salesforce Classic, Visualforce “owns” the page, the request, and the environment. Visualforce is the application container. But in the Salesforce mobile app and Lightning Experience, Visualforce runs inside an iframe that’s inside the larger /lightning container. <!-- document id=0afccd971813f05e48d56b9222cd30b1bad0ba889ba8d6172ea1d0177bba1424 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-ls-intro.md --> # Salesforce Scheduler Resources Use Salesforce Scheduler REST APIs to get appointment time slots or available service resources based on work type groups and service territories. - **[Scheduling](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-ls-scheduling.md)** Returns a list of available Salesforce Scheduler REST resources and corresponding URIs. This resource is available in REST API version 45.0 and later. - **[Get Appointment Slots](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-ls-getappointmentslots.md)** Returns a list of available appointment time slots for a resource based on given work type group or work type and service territories. - **[Get Appointment Candidates](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-ls-getappointmentcandidates.md)** Returns a list of service resources (appointment candidates) based on work type group or work type and service territories. - **[Request Bodies](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-bodies-ls.md)** - **[Response Bodies](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-ls.md)** **See Also** - [*Connect REST API Developer Guide*: Lightning Scheduler Resources](https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_lightning_scheduler.htm) <!-- document id=cf729970f90b082d13cb86f8de2e542ba88ce0562ab424b7c953302bd4048f89 url=/developer/current/en-us/platform/api/guides/api/guidelines/salesforcecom-settings.md --> # Salesforce Settings Most processing takes place in the database. Setting these parameters correctly will help the database process as quickly as possible: - **Enable or Disable the Most Recently Used (MRU) functionality.** Records marked as most recently used (MRU) are listed in the “Recent Items” section of the sidebar in the Salesforce user interface. Check that you are not enabling it for calls where it is not needed. In API version 7.0 and above, MRU functionality is disabled by default. To enable the MRU functionality, create this header and set the [updateMru](https://developer.salesforce.com/docs/platform/api/header/sforce-api-header-mruheader.md) to `true`. The following sample shows how to use MRU functionality: <!-- otherprops: java set_clipboard --> ```codesegment public void mruHeaderSample() { connection.setMruHeader(true); Account account = new Account(); account.setName("This will be in the MRU"); try { SaveResult[] sr = connection.create(new SObject[]{account}); System.out.println("ID of account added to MRU: " + sr[0].getId()); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` - **Log in as a user with the “Modify All Data” permission to avoid sharing rules.** If the client application logs in as a user who has access to data via a sharing rule, then the API must issue an extra query to check access. To avoid this, log in as a user with the “Modify All Data” permission. In general, fewer sharing rules quickens load speeds, as there are fewer operations that have to be performed when setting properties such as ownership. Alternatively, you can set organization-wide defaults for some objects as public read/write for the duration of the load. For more information, see “Set Your Internal Organization-Wide Sharing Defaults” in the Salesforce online help. - **Avoid workflow or assignment rules.** Anything that causes a post-operation action slows down the load. You can temporarily disable automatic rules if the loaded objects are exempt from them. - **Avoid triggering cascading updates.** For example, if you update the owner of an account, the contacts and opportunities associated with that account may also require updates. Instead of updating a single object, the client application must access multiple objects, which slows down the load. The Lightning Platform Data Loader is a good reference for data loading. It disables the MRU, uses HTTP/1.1 persistent connections, and applies GZIP compression on the request and response. If you are performing a data load, or are looking at a place to start when writing your own Java integration, the Lightning Platform Data Loader can serve as a fast and reliable solution. For more information about the Lightning Platform Data Loader, see: Data Loader in the Salesforce online help. <!-- document id=c5874affcf1005b2df6ade432cc223d901f47b34ba8f4bb4628e87dc132ba4aa url=/developer/current/en-us/platform/api-rest/guides/resources/resources-survey-translation.md --> # Salesforce Surveys Translation Resources Use REST APIs to translate survey fields, view, update, or delete translated survey fields. The translated values of surveys fields are stored in Flow fields. The following survey fields can be translated: - Survey name - Pause message - Welcome message - Questions - Answer choices and ranking items - Thank you message - **[Add or Change the Translation of a Survey Field](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-add-change.md)** 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. - **[Add or Update the Translated Value of Multiple Survey Fields in One or More Languages](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-add-change-multiple.md)** 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. - **[Delete the Translated Value of a Survey Field](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-delete.md)** After a survey field is translated into a particular language, you can delete the translated value of the survey field. This resource is available in REST API version 48.0 and later. - **[Delete the Translated Value of Multiple Survey Fields in One or More Languages](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-delete-multiple.md)** After survey fields are translated into one or more languages, you can delete the translated values of multiple survey fields. This resource is available in REST API version 48.0 and later. - **[Get Translated Value of a Survey Field](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-view.md)** After a survey field is translated into a particular language, you can use this resource to get the translated value of the survey field. This resource is available in REST API version 48.0 and later. - **[Get the Translated Values of Multiple Survey Fields in One or More Languages](https://developer.salesforce.com/docs/platform/api-rest/guide/request-survey-translate-view-multiple.md)** After survey fields are translated into one or more languages, you can view the translated values of multiple survey fields in the translated languages. This resource is available in REST API versions 48.0 and later. <!-- document id=530adf2f5c42c380a44f7bf00b290608c66d1da161aaa8cbcfddee52d8f1534c url=/developer/current/en-us/platform/platform-events/guides/platform-events/objects/sforce-api-objects-salesmeetingbookedevent.md --> # SalesMeetingBookedEvent Notifies subscribers when a lead books a sales meeting via an inbound web agent or other service. This object is available in API version 65.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/SalesMeetingBookedEvent` ## Event Delivery Allocation Enforced Yes ## Special Access Rules To use this object, [Turn on Salesforce Inbox](https://help.salesforce.com/s/articleView?id=sales.inbox_setup_start_setup_assistant.htm&type=5) in Setup. Users need the Use Inbox permission to subscribe to these events. ## Fields ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `Orchestrator` **Type:** string **Properties:** None **Description:** Required. The Salesforce tracking record created to start the meeting booking process. ### `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. ### `Target` **Type:** string **Properties:** None **Description:** Required. The contact or lead record being created or worked on to continue the meeting booking process. <!-- document id=8062c39737fb7c336c66f414c5db578eb7e7ece6810d2bcd170e2e43cb7228e9 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/canvas-app-saml-sso-intro.md --> # SAML Single Sign-On for Canvas Apps Whether you use signed request or OAuth authorization, you can use SAML-based single sign-on (SSO) to provide your users with a seamless authentication flow. You can leverage Salesforce as an identity provider or as a service provider. SAML SSO enables you to give your users automatic authentication into your canvas app via SAML and authentication into Salesforce via the signed request. SAML (Security Assertion Markup Language) is an XML-based standard for user authentication on the Web which allows the exchange of authorization data between two domains. With this feature you can create a canvas app that begins a standard SAML authentication flow when opened by a user. After this process completes, the user is authenticated into your Web application. For canvas apps that use signed request authentication, two methods that are included in the Canvas SDK enable your canvas app to call into Salesforce to receive a new signed request directly or enable Salesforce to repost the signed request to your Web application endpoint. This results in a complete end-to-end authentication flow. - `refreshSignedRequest` Method - : Returns a new signed request via a callback. After the SAML SSO process is completed, your app can call this method and receive a new signed request. This method is intended for developers who need to retrieve the signed request by using a more client-side JavaScript approach. (The Canvas SDK sends the signed request to your app.) - `repost` Method - : Requests the parent window to initiate a POST to your canvas app and reloads the app page with a refreshed signed request. After the SAML SSO process is completed, your app can call this method and a new signed request is sent to your app via a POST. This method is for developers who want to retrieve the signed request using a more server-side approach. (Salesforce POSTs the signed request to your server.) **note:** The SAML Initiation Method `Identity Provider Initiated` is not supported for canvas apps on Lightning Platform sites. <!-- document id=4008b6b20c6cef432547a481eedc5e62aed0acafca43d1f7539ae1c73fdfaca9 url=/developer/current/en-us/platform/api-asynch/guides/api-asynch/code/asynch-api-code.md --> # Sample Client Application Using Java Use this code sample to create a test client application that inserts a number of account records using the REST-based Bulk API. In addition to the step-by-step instructions that follow, the end of this section provides the complete code to make copying and pasting easier for you. **note:** Before you begin building an integration or other client application: - Install your development platform according to its product documentation. - Read through all the steps before creating the test client application. You may also wish to review the rest of this document to familiarize yourself with terms and concepts. 1. [Set Up Your Client Application](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-code-set-up-client.md) The Bulk API uses HTTP GET and HTTP POST methods to send and receive XML or JSON content, so it’s simple to build clients in the language of your choice. This task uses a Java sample and the Salesforce Web Service Connector (WSC) toolkit provided by Salesforce to simplify development. WSC is a high-performing web service client stack implemented using a streaming parser. The toolkit has built-in support for the basic operations and objects used in the Bulk API. 2. [Walk Through the Sample Code](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-code-walkthrough.md) After you set up your client, you can build client applications that use the Bulk API. Use the sample to create a client application. Each section steps through part of the code. The complete sample is included at the end. <!-- document id=7533872259f432f21a4d1f3b3bd814a6b214ac7d9ff8d5df32d00e77e7a13664 url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-code-with-sharing__give-read-access-to-guest-users.md --> # Sample Code With Sharing: Give Guest Users Access to Read Records In this collection of code samples, the guest user enters a date range and then views events within that range. The guest user has read access to the records via sharing rules. **important:** Before you give read access to guest users, see [Give Guest Users Access to Read Records](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-give-guest-users-read-access-to-records.md). ## Aura Component: DisplayEvents.cmp This sample Aura component displays two `lightning:input` components, where the user enters a start and end date to view events. The `lightning:card` component displays each event’s `StartDateTime`, `EndDateTime`, `Subject`, and `Location`. ```html <aura:component controller="GuestUserEventsAuraController"> <aura:attribute name="events" type="Event[]"/> <aura:attribute name="StartDate" type="String" default=""/> <aura:attribute name="EndDate" type="String" default=""/> <lightning:input type="datetime" name="StartDate" value="{!v.StartDate}" aura:id="StartDate" label="Start after: " required="true"/> <lightning:input type="datetime" name="EndDate" value="{!v.EndDate}" aura:id="EndDate" label="End before: " required="true"/> <lightning:button name="Submit" variant="brand" label="Find events" title="Find events" onclick="{!c.handleSearch}"/> <lightning:card title="Events"> <p class="slds-p-horizontal--small"> <aura:iteration items="{!v.events}" var="event"> {!event.Subject} ({!event.Location}) starts at {!event.StartDateTime} and ends at {!event.EndDateTime} <br/> </aura:iteration> </p> </lightning:card> </aura:component> ``` ## Component Controller: DisplayEventsController.js This sample JavaScript controller processes events for the Aura component and calls the methods in the helper file. ```javascript ({ handleSearch : function(component, event, helper) { helper.doSearch(component, event, helper); } }) ``` ## JavaScript Helper: DisplayEventsHelper.js This JavaScript helper creates an asynchronous request to find events within the two timestamps that the user submitted and defines the actions to take when the request completes. ```javascript ({ doSearch : function(component, event, helper) { var start_date = component.find("StartDate").get("v.value"); var end_date = component.find("EndDate").get("v.value"); var action = component.get("c.searchEvents"); action.setParams({ "start_date": start_date, "end_date": end_date }); action.setCallback(this, function(response){ component.set("v.events", response.getReturnValue()); }); $A.enqueueAction(action); } }) ``` ## Apex Controller: GuestUserEventsAuraController.cls This sample Apex controller receives the call to find records from the JavaScript helper. It selects events that match these criteria: - The event’s `StartDateTime` is greater than the `Start_Date` parameter. - The event’s `EndDateTime` is less than the `End_Date` parameter. - The event’s `isPrivate` value is `False`. - The event’s `isArchived` value is `False`. The query returns these fields for each of the events: - `StartDateTime` - `EndDateTime` - `Location` - `Subject` - `Id` Because the guest users don’t need the record ID, a `for` loop copies all the other fields to a new Event object. Then, we add the new objects to a new list and return that list to the client. The guest user has access to the records with sharing rules, so we define the class with the `with sharing` keyword. **note:** Any system or individual on the internet can invoke `@AuraEnabled` methods. Protect the execution of the method by implementing procedural access checks. Make sure that the query selects only the desired records and only the required fields. <!-- otherprops: apex_code --> ```class public with sharing class GuestUserEventsAuraController { @AuraEnabled public static List<Event> searchEvents(Datetime start_date, Datetime end_date){ List<Event> results = [SELECT Event.Subject, Event.StartDateTime, Event.EndDateTime, Event.Location FROM Event WHERE Event.EndDateTime<:end_date AND Event.StartDateTime>:start_date AND Event.isPrivate=False AND Event.isArchived=False]; List<Event> filtered_events = new List<Event>(); for (Event event : results) { Event new_event = new Event(Subject = event.Subject, StartDateTime = event.StartDateTime, EndDateTime = event.EndDateTime, Location = event.Location); filtered_events.add(new_event); } return filtered_events; } } ``` **See Also** - [*Salesforce Developers Wiki*: Enforcing CRUD and FLS](https://developer.salesforce.com/wiki/enforcing_crud_and_fls) - [*Salesforce Help*: Secure Guest Users’ Sharing Settings and Record Access](https://help.salesforce.com/articleView?id=networks_secure_guest_user_sharing.htm) - [*Salesforce Help*: Sharing Rules](https://help.salesforce.com/articleView?id=security_about_sharing_rules.htm) - [*Apex Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) - [*Lightning Aura Components Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/intro_framework.htm) <!-- document id=e2c7b0c41577cfa4ef729fc52b089834790e167b702288d27afe97a650fc5995 url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-code-guest-users-create-read-same-transaction.md --> # Sample Code Without Sharing: Give Guest Users Access to Create and Read Records in the Same Transaction In this collection of code samples, the guest user enters details to report a support issue and Apex code creates a case. An Apex method retrieves the new record and Aura components display parts of the record to the guest user after creation. The Apex code runs without sharing because we aren’t relying on object permissions and platform sharing to allow the guest user to access the record. ## Aura Component: CreateCase.cmp This sample Aura component displays several components where the user enters details about the case. After creation, the `lightning:card` component displays the new case’s case number and status. ```html <aura:component controller="GuestUserCreateCase"> <aura:attribute name="caseNumber" type="String"/> <aura:attribute name="status" type="String"/> <aura:attribute name="subject" type="String" default=""/> <aura:attribute name="description" type="String" default=""/> <aura:attribute name="email" type="String" default=""/> <aura:attribute name="name" type="String" default=""/> <aura:attribute name="reason" type="String"/> <aura:attribute name="type" type="String" default=""/> <lightning:select name="select" label="Reason" required="true" value="{!v.reason}" aura:id="reason"> <option value="installation">Installation</option> <option value="equipmentcomplexity">Equipment Complexity</option> <option value="performance">Performance</option> <option value="breakdown">Breakdown</option> <option value="equipmentdesign">Equipment Design</option> <option value="feedback">Feedback</option> <option value="other">Other</option> </lightning:select> <lightning:select name="type" label="Type" required="true" value="{!v.type}" aura:id="type"> <option value="mechanical">Mechanical</option> <option value="electrical">Electrical</option> <option value="electronic">Electronic</option> <option value="structural">Structural</option> <option value="other">Other</option> </lightning:select> <lightning:input type="email" name="email" required="true" value="{!v.email}" aura:id="email" label="Where should we send email updates?"/> <lightning:input name="name" label="Name" required="true" value="{!v.name}" aura:id="name"/> <lightning:input name="subject" label="Subject" required="true" value="{!v.subject}" aura:id="subject"/> <lightning:textarea name="description" required="true" label="Description" value="{!v.description}" aura:id="description"/> <lightning:button name="submit" variant="brand" label="Submit case" title="Submit case" onclick="{!c.submitCase}"/> <aura:if isTrue="{!v.caseNumber}"> <lightning:card title="Case"> <p class="slds-p-horizontal--small"> {!v.caseNumber} has status {!v.status}. </p> </lightning:card> </aura:if> </aura:component> ``` ## Component Controller: CreateCaseController.js This sample JavaScript controller processes events for the Aura component and calls the methods in the helper file. ```javascript ({ submitCase : function(component, event, helper) { helper.makeCase(component, event, helper); } }) ``` ## JavaScript Helper: DisplayCaseHelper.js This JavaScript helper creates an asynchronous request to create a case with the submitted data. When the request completes, the callback stores the case number and case status in variables used by the Aura component. ```javascript ({ makeCase : function(component, event, helper) { var subject = component.get("v.subject"); var description = component.get("v.description"); var email = component.get("v.email"); var name = component.get("v.name"); var reason = component.get("v.reason"); var type = component.get("v.type"); var action = component.get("c.CreateCase"); action.setParams({ "subject": subject, "description": description, "email": email, "name": name, "reason": reason, "caseType": type }); action.setCallback(this, function(response){ component.set("v.caseNumber", response.getReturnValue()[0]); component.set("v.status", response.getReturnValue()[1]); }); $A.enqueueAction(action); } }) ``` ## Apex Controller: GuestUserCreateCase.apxc This sample Apex controller creates the record, retrieves the new record, and returns the required fields from the new record to the client. Because object permissions and platform sharing aren’t used, this controller runs without sharing. To avoid unintended exposure of record data, the `CreateCase` method returns only the `CaseNumber` and `Status` fields. **note:** Any system or individual on the internet can invoke `@AuraEnabled` classes. Make sure that the method returns only the required fields from the new record. <!-- otherprops: apex_code --> ```class public without sharing class GuestUserCreateCase { @AuraEnabled public static List<String> CreateCase(String subject, String description, String email, String name, String reason, String caseType, String phone){ Case new_case = new Case(Subject=subject, Description=description, SuppliedEmail=email, SuppliedName=name, Reason=reason, Type=caseType, SuppliedPhone=phone); insert new_case; List<Case> results = getCase(new_case.Id); List<String> response = new List<String>(); response.add(results[0].CaseNumber); response.add(results[0].Status); return response; } private static List<Case> getCase(String caseID) { List<Case> results = [SELECT CaseNumber, Status FROM Case WHERE Case.Id=:caseID]; return results; } } ``` **See Also** - [*Salesforce Help*: Secure Guest Users’ Sharing Settings and Record Access](https://help.salesforce.com/articleView?id=networks_secure_guest_user_sharing.htm) - [*Apex Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) - [*Lightning Aura Component Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/intro_framework.htm) <!-- document id=a63dd8bb3584c9ae47c402bc52fc011c50f9abe41fcf6930e84f1636515a747f url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-code-guest-users-create-read-later.md --> # Sample Code Without Sharing: Give Guest Users Access to Create Records and Read Them Later These code samples support two separate interactions. In the first interaction, the guest user creates a case. To allow for future access, an Apex method replaces the record ID with an encrypted string. When the guest user wants to read the case later, they enter the encrypted string. An Apex method decrypts the string and uses it to retrieve the case. ## Aura Component: CreateCase.cmp This sample Aura component displays several components where a guest user can enter details about a new case or the token from an existing case. After record creation, `lightning:card` components display the new case’s encrypted token or the status of the case that matches the token. For demonstration purposes, this sample uses a field where the guest user can enter their case’s token. To implement this scenario, provide the guest user with a link that contains the token, and retrieve the token from the URL. ```html <aura:component controller="GuestUserCreateForLater"> <aura:attribute name="caseID" type="String"/> <aura:attribute name="case_status" type="String"/> <aura:attribute name="subject" type="String"/> <aura:attribute name="description" type="String"/> <aura:attribute name="email" type="String"/> Enter details to create a new case <lightning:input type="email" name="email" required="true" value="{!v.email}" aura:id="email" label="Where should we send email updates?"/> <lightning:input name="subject" label="Subject" required="true" value="{!v.subject}" aura:id="subject"/> <lightning:textarea name="description" required="true" label="Description" value="{!v.description}" aura:id="description"/> <lightning:button name="submit" variant="brand" label="Create case" title="Create case" onclick="{!c.submitCase}"/> <aura:if isTrue="{!v.caseID}"> <lightning:card title="Case"> <p class="slds-p-horizontal--small"> New case created: <p>{!v.caseID}</p> </p> </lightning:card> </aura:if> Or enter an existing case token to view the status of the case <lightning:textarea name="existing_case" required="false" label="Existing case token" aura:id="existing_case"/> <lightning:button name="submit" variant="brand" label="Lookup case" title="Lookup case" onclick="{!c.lookupCase}"/> <aura:if isTrue="{!v.case_status}"> <lightning:card title="Case"> <p class="slds-p-horizontal--small"> Case status: <p>{!v.case_status}</p> </p> </lightning:card> </aura:if> </aura:component> ``` ## Component Controller: CreateCaseController.js This sample JavaScript controller processes events for the Aura component and calls the methods in the helper file. ```javascript ({ submitCase : function(component, event, helper) { helper.makeCase(component, event, helper); } lookupCase : function(component,event,helper){ helper.getCase(component,event,helper); } }) ``` ## JavaScript Helper: DisplayCaseHelper.js This JavaScript helper has two methods: **`makeCase()`** The `makeCase()` method creates an asynchronous request to create a case with the submitted data. When the request completes, the callback stores the new case’s unique token in the `caseID` field in a variable used by the Aura component. **`getCase()`** The `getCase()` method uses a token entered by the guest user to asynchronously retrieve a case that matches the token. The method’s callback catches the response from the Apex method and stores the value in the `case_status` variable. ```javascript ({ makeCase : function(component, event, helper) { var subject = component.find("subject").get("v.value"); var description = component.find("description").get("v.value"); var email = component.find("email").get("v.value"); var action = component.get("c.CreateCase"); action.setParams({ "subject": subject, "description": description, "email": email }); action.setCallback(this, function(response){ component.set("v.caseID", response.getReturnValue()); }); $A.enqueueAction(action); }, getCase : function(component,event,helper){ var case_token = component.find("existing_case").get("v.value"); var action = component.get("c.GetCase"); action.setParams({ "token":case_token }); action.setCallback(this, function(response){ component.set("v.case_status", response.getReturnValue()); }); $A.enqueueAction(action); } }) ``` ## Apex Controller: GuestUserCreateForLater.cls This sample Apex controller receives calls to create and retrieve cases. It uses the [User Encryption Decryption](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000FYjU2UAL) AppExchange package to encrypt and decrypt data. **`CreateCase()`** The `CreateCase()` Apex method creates a case with the guest user’s input. After record creation, it generates an encrypted string from the record ID, the record’s `CreatedDate` field, and the current timestamp. The Apex method returns the encrypted string. **`GetCase()`** The `GetCase()` method decrypts the provided string, validates the results, and passes the decrypted record ID and created timestamp to a helper method to retrieve the original record. The response is the status of the record. Define the class with the `without sharing` keyword because we aren’t relying on object permissions and platform sharing to create and access records. **note:** Any system or individual on the internet can invoke `@AuraEnabled` methods. Make sure that the query can retrieve only the newly created record, and select only the required fields. ```apex public class without sharing GuestUserCreateForLater { @AuraEnabled public static String CreateCase(String subject, String description, String email){ Case new_case = new Case(Subject=subject, Description=description, SuppliedEmail=email); insert new_case; List<Case> results = getCase(new_case.Id); String encryptedID = ued.UserCryptoHelper.doEncrypt(results[0].Id+'|'+ results[0].CreatedDate.getTime() +'|'+System.DateTime.now().getTime()); return encryptedID; } public static final Long validTimestampMinutes = 10; @AuraEnabled public static String GetCase(String token){ String status = 'Case not found'; String decrypted_token = ''; try { decrypted_token = ued.UserCryptoHelper.doDecrypt(token); } catch(Exception e) { return status; } String[] decrypted_parts = decrypted_token.split('\\|'); String decryptedRecordId = decrypted_parts[0]; String created_timestamp = decrypted_parts[1]; String original_request_timestamp = decrypted_parts[2]; if( isTimestampValid(System.Long.valueOf(original_request_timestamp)) ){ List<Case> caseList = getCase(decryptedRecordId, created_timestamp); if(caseList.size() == 1){ status = caseList[0].Status; }else{ status = 'Case not found'; } } return status; } private static List<Case> getCase(String caseID, Datetime created_date) { List<Case> results = [SELECT Case.CaseNumber, Case.CreatedDate, Case.Status FROM Case WHERE Case.Id=:caseID AND Case.CreatedDate=:created_date]; return results; } private static Boolean isTimestampValid(Long timestamp) { return ((System.now().getTime() - timestamp) / 60000) < validTimestampMinutes; } } ``` **note:** If you’re loading highly sensitive information, consider one of these additional measures to increase security. - Ask the user to enter additional information related to the data that they’re attempting to read or modify, which only they know. - Require the user to log in to read or modify the data. **See Also** - [*Salesforce Help*: Secure Guest Users’ Sharing Settings and Record Access](https://help.salesforce.com/articleView?id=networks_secure_guest_user_sharing.htm) - [*Apex Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) - [*Lightning Aura Components Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/intro_framework.htm) <!-- document id=72d0374ee7b8dc81bb994cc0b70a05b0bd46cdd3d4cdc51fbaae512182cad1b1 url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-code-guest-users-create-update-later.md --> # Sample Code Without Sharing: Give Guest Users Access to Create Records and Update Them Later These code samples support two separate interactions. In the first interaction, the guest user creates a case. For security reasons, an Apex method replaces the record ID with an encrypted string. When the guest user wants to close the case later, they enter that encrypted string. An Apex method decrypts the string to get the record ID, uses the record ID to select the case, and updates the case’s status. ## Aura Component: CreateCase.cmp This sample Aura component displays components for record creation and closure. To create a case, the guest user uses components to enter case details. After record creation, `lightning:card` components display the new case’s encrypted token or the status of the case that matches the token. For demonstration purposes, this sample displays a component where the guest user enters the case’s token directly. To implement this scenario, provide the guest user with a link that contains the token, and retrieve the token from the URL. ```html <aura:component controller="GuestUserCreateForLater"> <aura:attribute name="caseID" type="String"/> <aura:attribute name="case_status" type="String"/> <aura:attribute name="subject" type="String"/> <aura:attribute name="description" type="String"/> <aura:attribute name="email" type="String"/> Enter details to create a new case <lightning:input type="email" name="email" required="true" value="{!v.email}" aura:id="email" label="Where should we send email updates?"/> <lightning:input name="subject" label="Subject" required="true" value="{!v.subject}" aura:id="subject"/> <lightning:textarea name="description" required="true" label="Description" value="{!v.description}" aura:id="description"/> <lightning:button name="submit" variant="brand" label="Create case" title="Create case" onclick="{!c.submitCase}"/> <aura:if isTrue="{!v.caseID}"> <lightning:card title="Case"> <p class="slds-p-horizontal--small"> New case created: <p>{!v.caseID}</p> </p> </lightning:card> </aura:if> Or enter an existing case token to close the case <lightning:textarea name="existing_case" required="false" label="Existing case token" aura:id="existing_case"/> <lightning:button name="submit" variant="brand" label="Close case" title="Close case" onclick="{!c.updateCase}"/> <aura:if isTrue="{!v.case_status}"> <lightning:card title="Case"> <p class="slds-p-horizontal--small"> Case status: <p>{!v.case_status}</p> </p> </lightning:card> </aura:if> </aura:component> ``` ## Component Controller: CreateCaseController.js This sample JavaScript controller processes events for the Aura component and calls the methods in the helper file. ```javascript ({ submitCase : function(component, event, helper) { helper.makeCase(component, event, helper); }, updateCase : function(component,event,helper){ helper.updateCase(component,event,helper); } }) ``` ## JavaScript Helper: CaseHelper.js This JavaScript helper has two methods: **`makeCase()`** The `makeCase()` method creates an asynchronous request to create a case with the submitted data. When the request completes, the callback stores the new case’s unique token in the `caseID` field in a variable used by the Aura component. **`updateCase()`** The `updateCase()` method uses a token entered by the guest user to asynchronously update the case that matches the token. The method’s callback catches the response from the Apex method and stores the value in the `case_status` variable. ```javascript ({ makeCase : function(component, event, helper) { var subject = component.find("subject").get("v.value"); var description = component.find("description").get("v.value"); var email = component.find("email").get("v.value"); var action = component.get("c.CreateCase"); action.setParams({ "subject": subject, "description": description, "email": email }); action.setCallback(this, function(response){ component.set("v.caseID", response.getReturnValue()); }); $A.enqueueAction(action); }, updateCase : function(component,event,helper){ var case_token = component.find("existing_case").get("v.value"); var action = component.get("c.UpdateCase"); action.setParams({ "token":case_token }); action.setCallback(this, function(response){ component.set("v.case_status", response.getReturnValue()); }); $A.enqueueAction(action); } }) ``` ## Apex Controller: GuestUserCreateForLater.cls This sample Apex controller receives calls to create and update cases. It uses the [User Encryption Decryption](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000FYjU2UAL) AppExchange package to encrypt and decrypt data. **`CreateCase()`** The `CreateCase()` Apex method creates a case with the guest user’s input. After record creation, it generates an encrypted string from the record ID, the record’s `CreatedDate` field, and the current timestamp. The Apex replaces the new case’s ID with the encrypted string. **`UpdateCase()`** The `UpdateCase()` method decrypts the provided string, validates the results, and uses the information to update the original record’s status. The response is the status of the record or an error message, if one occurred. Define the class with the `with sharing` keyword because it doesn’t directly access the records. **note:** Any system or individual on the internet can invoke `@AuraEnabled` classes. Make sure that the query can update only the correct record. <!-- otherprops: apex_code --> ```class public with sharing class GuestUserCreateForLater { @AuraEnabled public static String CreateCase(String subject, String description, String email){ Case new_case = new Case(Subject=subject, Description=description, SuppliedEmail=email); insert new_case; List<Case> results = GuestUserCaseHelperWS.getCase(new_case.Id); String encryptedID = ued.UserCryptoHelper.doEncrypt(results[0].Id+'|'+ results[0].CreatedDate.getTime() +'|'+System.DateTime.now().getTime()); return encryptedID; } public static final Long validTimestampMinutes = 10; @AuraEnabled public static String UpdateCase(String token){ String status = 'Case not found'; String decrypted_token = ''; try { decrypted_token = ued.UserCryptoHelper.doDecrypt(token); } catch(Exception e) { return status; } String[] decrypted_parts = decrypted_token.split('\\|'); String decryptedRecordId = decrypted_parts[0]; String created_timestamp = decrypted_parts[1]; String original_request_timestamp = decrypted_parts[2]; if( isTimestampValid(System.Long.valueOf(original_request_timestamp))) { List<Case> caseList = GuestUserCaseHelperWS.getCase(decryptedRecordId, created_timestamp); if(caseList.size() == 1){ Case case_to_update = caseList[0]; case_to_update.Status = 'Closed'; try { GuestUserCaseHelperWS.updateCase(case_to_update); status = 'Closed'; } catch(DmlException e){ System.debug('An unexpected error has occurred: ' + e.getMessage()); } }else{ status = 'Case not found'; } } return status; } private static Boolean isTimestampValid(Long timestamp) { return ((System.now().getTime() - timestamp) / 60000) < validTimestampMinutes; } } ``` ## Apex Helper Class: GuestUserCaseHelperWS.apxc This sample Apex helper class defines methods that retrieve a record by its ID and update a record. The Apex controller calls this method. Define the class with the `without sharing` keyword so that it can retrieve and update the record without requiring sharing. ```apex public without sharing class GuestUserCaseHelperWS { public static List<Case> getCase(String caseID, Datetime created_date) { List<Case> results = [SELECT Case.CaseNumber, Case.CreatedDate, Case.Status FROM Case WHERE Case.Id=:caseIDAND Case.CreatedDate=:created_date]; return results; } public static Case updateCase(Case case_to_update) { update case_to_update; return case_to_update; } } ``` **See Also** - [*Salesforce Help*: Secure Guest Users’ Sharing Settings and Record Access](https://help.salesforce.com/articleView?id=networks_secure_guest_user_sharing.htm) - [*Apex Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) - [*Lightning Aura Components Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/intro_framework.htm) <!-- document id=52558d8f248aedb15c3556e11db520b628dc52102f30bcaf86590df69acc5a7b url=/developer/current/en-us/platform/api/guides/api/partner/sample-create-call.md --> # Sample create Call The following Java and C# examples show how to use the [`create()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-create.md) call for the partner WSDL. Each example creates a contact record with several fields. It iterates through the results of the create call and checks whether the operation was successful or not. If the create operation was successful, it writes the ID of the contact created to the console. Otherwise, it iterates through the errors and writes details of each error to the console. In this case, the output of the example is the ID of the new contact. To execute the sample method, you can use the corresponding Java or C# template class provided in [Examples Using the Partner WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-partner-examples.md). ## Java Example <!-- otherprops: java set_clipboard --> ```codesegment public String createSample() { String result = null; try { // Create a new sObject of type Contact // and fill out its fields. SObject contact = new SObject(); contact.setType("Contact"); contact.setField("FirstName", "Otto"); contact.setField("LastName", "Jespersen"); contact.setField("Salutation", "Professor"); contact.setField("Phone", "(999) 555-1234"); contact.setField("Title", "Philologist"); // Add this sObject to an array SObject[] contacts = new SObject[1]; contacts[0] = contact; // Make a create call and pass it the array of sObjects SaveResult[] results = partnerConnection.create(contacts); // Iterate through the results list // and write the ID of the new sObject // or the errors if the object creation failed. // In this case, we only have one result // since we created one contact. for (int j = 0; j < results.length; j++) { if (results[j].isSuccess()) { result = results[j].getId(); System.out.println( "\nA contact was created with an ID of: " + result ); } else { // There were errors during the create call, // go through the errors array and write // them to the console for (int i = 0; i < results[j].getErrors().length; i++) { Error err = results[j].getErrors()[i]; System.out.println("Errors were found on item " + j); System.out.println("Error code: " + err.getStatusCode().toString()); System.out.println("Error message: " + err.getMessage()); } } } } catch (ConnectionException ce) { ce.printStackTrace(); } return result; } ``` ## C# Example <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void createSample() { try { // Create a new sObject of type Contact // and fill out its fields. sObject contact = new sforce.sObject(); System.Xml.XmlElement[] contactFields = new System.Xml.XmlElement[6]; // Create the contact's fields System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); contactFields[0] = doc.CreateElement("FirstName"); contactFields[0].InnerText = "Otto"; contactFields[1] = doc.CreateElement("LastName"); contactFields[1].InnerText = "Jespersen"; contactFields[2] = doc.CreateElement("Salutation"); contactFields[2].InnerText = "Professor"; contactFields[3] = doc.CreateElement("Phone"); contactFields[3].InnerText = "(999) 555-1234"; contactFields[4] = doc.CreateElement("Title"); contactFields[4].InnerText = "Philologist"; contact.type = "Contact"; contact.Any = contactFields; // Add this sObject to an array sObject[] contactList = new sObject[1]; contactList[0] = contact; // Make a create call and pass it the array of sObjects SaveResult[] results = binding.create(contactList); // Iterate through the results list // and write the ID of the new sObject // or the errors if the object creation failed. // In this case, we only have one result // since we created one contact. for (int j = 0; j < results.Length; j++) { if (results[j].success) { Console.Write("\nA contact was created with an ID of: " + results[j].id); } else { // There were errors during the create call, // go through the errors array and write // them to the console for (int i = 0; i < results[j].errors.Length; i++) { Error err = results[j].errors[i]; Console.WriteLine("Errors were found on item " + j.ToString()); Console.WriteLine("Error code is: " + err.statusCode.ToString()); Console.WriteLine("Error message: " + err.message); } } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } } ``` <!-- document id=a23c27b27ac4309a209a3e2ffb98e1133b6ddf954bc55f60d72a0b513d714f47 url=/developer/current/en-us/platform/api-asynch/guides/api-bulk-v2/datafiles/datafiles-csv-samples.md --> # Sample CSV Files These examples demonstrate different ways to use CSV data with Bulk API 2.0. ## Simple CSV This example contains three Account records and specifies the Name, Description, and NumberOfEmployees fields for each record. ```nolang Name,Description,NumberOfEmployees TestAccount1,Description of TestAccount1,30 TestAccount2,Another description,40 TestAccount3,Yet another description,50 ``` A job that uses this CSV data might be defined with the following job properties. ```nolang { "object" : "Account", "contentType" : "CSV", "operation" : "insert" } ``` ## CSV with Alternate Line Ending This example contains two Contact records and specifies three fields for each record. The data was created on a Windows platform, and each line ends with a carriage return and line feed. The carriage return is displayed as “^M” in this example. ```nolang FirstName,LastName,Description^M Tom,Jones,Branding guru^M Ian,Dury,Fuzzy logic expert^M ``` A job that uses this CSV data and specifies that carriage return + line feed is used as the line ending sequence would use the following job properties. ```nolang { "object" : "Contact", "contentType" : "CSV", "operation" : "insert", "lineEnding" : "CRLF" } ``` ## CSV with Semicolon Delimiter and Escaped Fields This example contains two Contact records and specifies five fields for each record. The field delimiter is a semicolon instead of a comma. The Description fields contain characters that must be escaped using double quotes, including a line break in the second record. ```nolang FirstName;LastName;Title;Birthdate;Description Tom;Jones;Senior Director;1940-06-07Z;"Self-described as ""the top"" branding guru" Ian;Dury;Chief Imagineer;1965-12-11Z;"Expert in fuzzy logic design; Knowledgeable in AI Influential in technology purchases." ``` A job that uses this CSV data and specifies that semicolon is used as the column delimiter would use the following job properties. ```nolang { "object" : "Contact", "contentType" : "CSV", "operation" : "insert", "columnDelimiter" : "SEMICOLON" } ``` ## CSV with Relationship Field This example contains two Contact records and specifies FirstName, LastName, and Owner.Email fields for each record. This example assumes a unique User record exists that has an Email value of “mfellow@salesforce.com”, and creates a relationship with this record and the Contact records. If the User record doesn’t exist, or if there are multiple User records with an Email value of “mfellow@salesforce.com”, the relationship can’t be created and the job fails. ```nolang FirstName,LastName,Owner.Email Joe,User,mfellow@salesforce.com Jane,User,mfellow@salesforce.com ``` A job that uses this CSV data might be defined with the following job properties. ```nolang { "object" : "Contact", "contentType" : "CSV", "operation" : "insert" } ``` ## CSV for Upsert Using External IDs This example contains three Contact records and specifies FirstName, LastName, Phone, and ExternalId\_\_c for each record. This example assumes the custom ExternalId\_\_c external ID field has been added to Contact. ```nolang FirstName,LastName,Phone,ExternalId__c Mark,Brown,4155558787,"1001" Dave,Stillman,4155552212,"1002" Joe,Smith,2125556363,"5001" ``` A job that uses this CSV data might be an upsert job defined with the following properties. ```nolang { "object" : "Contact", "externalIdFieldName" : "ExternalId__c", "contentType" : "CSV", "operation" : "upsert" } ``` You can also associate records using external IDs. For more information, see [Upserting Records and Associating with an External ID](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm). s <!-- document id=bf503e537f9289f197c1fb5a0bb1cebd64787a58cd145b2afa8d5cd0bd5308f0 url=/developer/current/en-us/platform/aura-platform/guides/aura/components/components-custom-for-app-builder-forecasts-page.md --> # Sample Custom Components for Forecasts Pages Review samples of custom Aura components that you can implement in Lightning forecasts pages. Lightning forecasts pages don’t support any standard or custom events published from custom components. Here’s an example of a custom Aura component you can include in your Lightning forecasts page. To appear on the page, custom Aura components implement `lightning:availableForForecastingPage`. This component applies the context of the selected forecast. <!-- otherprops: set_clipboard --> ```nolang <aura:component implements="lightning:availableForForecastingPage"> <lightning:messageChannel type="lightning__forecasting_flexipageUpdated" onMessage="{!c.handleMessage}" scope="APPLICATION"/> <aura:attribute name="ownerId" type="string" default="owner"/> <aura:attribute name="forecastingTypeId" type="string" /> <aura:attribute name="user" type="Object"/> <aura:attribute name="forecast" type="Object"/> <aura:handler name="init" value="{!this}" action="{!c.init}"/> <force:recordData aura:id="recordLoader" recordId="{!v.ownerId}" fields="Name, Email, Phone, Title" targetFields="{!v.user}" /> <force:recordData aura:id="recordLoader2" recordId="{!v.forecastingTypeId}" fields="DateType, RoleType, MasterLabel, IsAmount, IsActive" targetFields="{!v.forecast}" /> <div> <lightning:card iconName="standard:user" title="{!v.user.Name}" > <div class="slds-p-horizontal--small"> <p class="slds-truncate">Email : <lightning:formattedText title="Email" value="{!v.user.Email}" /></p> <p class="slds-truncate">Phone : <lightning:formattedText title="Phone" value="{!v.user.Phone}" /></p> <p class="slds-truncate">Title : <lightning:formattedText title="Title" value="{!v.user.Title}" /></p> </div> </lightning:card> </div> <div> <lightning:card iconName="standard:forecasts" title="{!v.forecast.MasterLabel}" > <div class="slds-p-horizontal--small"> <p class="slds-truncate">Role Type : <lightning:formattedText aura:id="roleType" title="RoleType" value="{!v.forecast.RoleType}" /></p> <p class="slds-truncate">Date Type : <lightning:formattedText title="DateType" value="{!v.forecast.DateType}" /></p> </div> </lightning:card> </div> </aura:component> ``` The component calls a JavaScript controller function, `handleMessage()`, on initialization. <!-- otherprops: set_clipboard --> ```nolang ({ /* This JavaScript controller is called on component initialization. It makes a call to the server to run the actions to display information. After the server returns the values, it sets the appropriate values to display on the client side. */ handleMessage : function(cmp, message, helper) { // Read the message argument to get the values in the message payload cmp.set("v.ownerId", message.getParam("forecastingOwnerId")); cmp.set("v.forecastingTypeId", message.getParam("forecastingTypeId")); var record = cmp.find("recordLoader"); record.set("v.recordId", cmp.get("v.ownerId")); record.reloadRecord(); var record2 = cmp.find("recordLoader2"); record2.set("v.recordId", cmp.get("v.forecastingTypeId")); record2.reloadRecord(); } }) ``` **See Also** - [*Lightning Web Components Dev Guide*: Use Components in Salesforce Targets](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use) <!-- document id=b25a28a488759d448ecc480979cb96216a073988a49123a77434c289b72ee69a url=/developer/current/en-us/platform/aura-platform/guides/aura/components/components-custom-for-app-builder-email-app-pane.md --> # Sample Custom Components for Outlook and Gmail Integration Review samples of custom Aura components that you can implement in the email application pane for Outlook integration and Gmail Integration. ## Apply the Selected Email Context Here’s an example of a custom Aura component you can include in your email application pane for the Outlook or Gmail integration. This component applies the context of the selected email or appointment. <!-- otherprops: set_clipboard --> ```xml <!-- customEmailPane.cmp --> <aura:component implements="clients:availableForMailAppAppPage,clients:hasItemContext"> <!-- Add these handlers to customize what happens when the attributes change <aura:handler name="change" value="{!v.subject}" action="{!c.handleSubjectChange}" /> <aura:handler name="change" value="{!v.people}" action="{!c.handlePeopleChange}" /> --> <div id="content"> <aura:if isTrue="{!v.mode == 'edit'}"> You are composing the following Item: <br/> <aura:set attribute="else"> You are reading the following Item: <br/> </aura:set> </aura:if> <h1><b>Email subject</b></h1> <span id="subject">{!v.subject}</span> <h1>To:</h1> <aura:iteration items="{!v.people.to}" var="to"> {!to.name} - {!to.email} <br/> </aura:iteration> <h1>From:</h1> {!v.people.from.name} - {!v.people.from.email} <h1>CC:</h1> <aura:iteration items="{!v.people.cc}" var="cc"> {!cc.name} - {!cc.email} <br/> </aura:iteration> <span class="greeting">New Email Arrived</span>, {!v.subject}! </div> </aura:component> ``` ## Display Record Data Based On Recipients In this example, the custom component displays account and opportunity information based on the email recipients’ email addresses. The component calls a JavaScript controller function, `handlePeopleChange()`, on initialization. <!-- otherprops: set_clipboard --> ```xml <!-- customEmailDisplay.cmp --> <!-- This component handles the email context on initialization. It retrieves accounts and opportunities based on the email addresses included in the email recipients list. It then calculates the account and opportunity ages based on when the accounts were created and when the opportunities will close. --> <aura:component implements="clients:availableForMailAppAppPage,clients:hasItemContext" controller="ComponentController"> <aura:handler name="init" value="{!this}" action="{!c.handlePeopleChange}" /> <aura:attribute name="accounts" type="List" /> <aura:attribute name="opportunities" type="List" /> <aura:iteration items="{!v.accounts}" var="acc"> {!acc.name} => {!acc.age} </aura:iteration> <aura:iteration items="{!v.opportunities}" var="opp"> {!opp.name} => {!opp.closesIn} Days till closing </aura:iteration> </aura:component> ``` The Apex controller includes Aura-enabled methods that accept a list of emails as parameters. It queries the Contact and OpportunityContactRoles objects using SOQL and assigns the results to a List variable. You can also modify the example with your own custom objects. <!-- otherprops: set_clipboard --> ```apex /*ComponentController.cls*/ public class ComponentController { /* This method searches for Contacts with matching emails in the email list, and includes Account information in the fields. Then, it filters the information to return a list of objects to use on the client side. */ @AuraEnabled public static List<Map<String, Object>> findAccountAges(List<String> emails) { List<Map<String, Object>> ret = new List<Map<String, Object>>(); List<Contact> contacts = [SELECT Name, Account.Name, Account.CreatedDate FROM Contact WHERE Contact.Email IN :emails]; for (Contact c: contacts) { Map<String, Object> item = new Map<String, Object>(); item.put('name', c.Account.Name); item.put('age', Date.valueOf(c.Account.CreatedDate).daysBetween( System.Date.today())); ret.add(item); } return ret; } /* This method searches for OpportunityContactRoles with matching emails in the email list. Then, it calculates the number of days until closing to return a list of objects to use on the client side. */ @AuraEnabled public static List<Map<String, Object>> findOpportunityCloseDateTime(List<String> emails) { List<Map<String, Object>> ret = new List<Map<String, Object>>(); List<OpportunityContactRole> contacts = [SELECT Opportunity.Name, Opportunity.CloseDate FROM OpportunityContactRole WHERE isPrimary=true AND Contact.Email IN :emails]; for (OpportunityContactRole c: contacts) { Map<String, Object> item = new Map<String, Object>(); item.put('name', c.Opportunity.Name); item.put('closesIn', System.Date.today().daysBetween( Date.valueOf(c.Opportunity.CloseDate))); ret.add(item); } return ret; } } ``` On component initialization, this JavaScript controller calls the helper method, `filterEmails()`, which builds a list of email addresses from the available people. The JavaScript controller then makes a call to the server to run the actions to display information. It calls the `findOpportunityCloseDateTime` method on the Apex controller to query the opportunities days until closing. It calls the `findAccountAges` method to query the accounts ages. Once the server returns the values, it sets the appropriate values to display on the client side. <!-- otherprops: set_clipboard --> ```javascript /* customEmailDisplayController.js */ ({ handlePeopleChange: function(component, event, helper){ var people = component.get("v.people"); var peopleEmails = helper.filterEmails(people); var action = component.get("c.findOpportunityCloseDateTime"); action.setParam("emails", peopleEmails); action.setCallback(this, function(response){ var state = response.getState(); if(state === "SUCCESS"){ component.set("v.opportunities", response.getReturnValue()); } else{ component.set("v.opportunities",[]); } }); $A.enqueueAction(action); var action = component.get("c.findAccountAges"); action.setParam("emails", peopleEmails); action.setCallback(this, function(response){ var state = response.getState(); if(state === "SUCCESS"){ component.set("v.accounts", response.getReturnValue()); } else{ component.set("v.accounts",[]); } }); $A.enqueueAction(action); } }) ``` This helper function filters emails from objects. <!-- otherprops: set_clipboard --> ```javascript /* customEmailDisplayHelper.js */({ filterEmails : function(people){ return this.getEmailsFromList(people.to).concat( this.getEmailsFromList(people.cc)); }, getEmailsFromList : function(list){ var ret = []; for (var i in list) { ret.push(list[i].email); } return ret; } }) ``` <!-- document id=022c071592accdb676f21647a0030f291974920e6dd006b554a19885afeaf503 url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-flow-with-sharing__give-read-access-to-guest-users.md --> # Sample Flow With Sharing: Give Guest Users Access to Read Records In this sample flow, the guest user enters a date range and then views events within that range. The guest user has read access to the records with sharing rules, so the guest user profile determines which fields the flow can access. **important:** Before you give read access to guest users, see [Give Guest Users Access to Read Records](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-give-guest-users-read-access-to-records.md). ![The sample flow with numbered elements](https://developer.salesforce.com/media/communities-dev/guest_users_flow_with_sharing_read_numbered.png) ## Flow Configuration Because the guest user has access to the records via sharing rules, set the **How to Run the Flow** setting to **User or System Context—Depends on How Flow is Launched**. ## Enter Date Range (1) The first element in the flow is a screen that displays start and end date input fields. The element saves the input dates in the variables `Start_Date` and `End_Date`. ## Get Events (2) The next element is a Get Records query that selects events if they match these criteria: - The event’s `StartDateTime` is greater than the `Start_Date` variable. - The event’s `EndDateTime` is less than the `End_Date` variable. - The event’s `isPrivate` value is `False`. - The event’s `isArchived` value is `False`. The element saves the selected events in the `GetEvents` variable. ## Loop Records (3) The Loop element loops over each event in the `GetEvents` variable. Inside the loop, the Assignment element appends each event’s `StartDateTime`, `EndDateTime`, `Subject`, and `Location` to a string. ## Show Events (4) The final element is a screen that displays the string that contains all the events. **See Also** - [*Salesforce Help*: Secure Guest Users’ Sharing Settings and Record Access](https://help.salesforce.com/articleView?id=networks_secure_guest_user_sharing.htm) - [*Salesforce Help*: Sharing Rules](https://help.salesforce.com/articleView?id=security_about_sharing_rules.htm) - [*Salesforce Help*: Which Context Do Flows Run In?](https://help.salesforce.com/articleView?id=flow_distribute_context.htm) - [*Salesforce Help*: Flow Elements](https://help.salesforce.com/articleView?id=flow_ref_elements.htm) <!-- document id=411c6fbb3674d4161f23e8d87cb40541cf6b22fad91c63c520a9edee7015bf3b url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-flow-guest-users-create-read-one-flow.md --> # Sample Flow Without Sharing: Give Guest Users Access to Create and Read Records in One Flow In this sample flow, the guest user enters details to report a support issue and the flow creates a case. After the guest user creates the record, a default active user becomes the owner of the record and the guest user doesn’t have direct access to it. The flow then retrieves the new case to get the case’s `CaseNumber` and `Status` fields and displays those fields to the guest user. Because the guest user doesn’t own the record after creation and the flow must retrieve the record, the flow runs without sharing. **important:** Before you give create and read access to guest users, read [Give Guest Users Access to Read Records](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-give-guest-users-read-access-to-records.md) and [Give Guest Users Access to Create Records](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-give-guest-users-access-to-create-records.md). ![The sample flow with numbered elements](https://developer.salesforce.com/media/communities-dev/guest_users_flow_without_sharing_create_read_numbered.png) ## Flow Configuration Because the flow creates a record and then retrieves the record without sharing, set the **How to Run the Flow** setting to **System Context Without Sharing—Access All Data**. ## Case Form (1) The first element in the flow is a screen that displays these input components: - A Text component for the company’s name - A Name component for the submitter’s name - An Email component for the submitter’s email address - A Phone component for the submitter’s phone number - A Picklist component with option values from the record type’s `Type_Options` field - A Picklist component with option values from the record type’s `Reason_Options` field - A Text component for the subject of the case - A Long Text Area component for the description of the case ## Assignment (2) The second element assigns the data from the input components to a new `Case` record variable. ## Create Records (3) The next element is a Create Records element that uses the `Case` record variable to create a Case record. In addition to the information entered by the guest user, set the element configuration to define the case’s origin field as `Web`. ## Get Records (4) The Get Records element retrieves the new record by its `Id` field that is automatically defined by the Create Records element. The retrieved record is stored in a new `Case` record variable. ## End Screen (5) The final screen element displays the Case’s `CaseNumber` and `Status` fields from the Get Record element’s `Case` record variable. **See Also** - [*Salesforce Help*: Which Context Do Flows Run In?](https://help.salesforce.com/articleView?id=flow_distribute_context.htm) - [*Salesforce Help*: Flow Elements](https://help.salesforce.com/articleView?id=flow_ref_elements.htm) - [*Salesforce Help*: Allow Guest Users to Access Flows](https://help.salesforce.com/articleView?id=rss_flow_guestuser.htm) - [*Salesforce Help*: Apex Actions](https://help.salesforce.com/articleView?id=flow_ref_elements_apex_invocable.htm) - [*Salesforce Help*: Flows in Transactions](https://help.salesforce.com/articleView?id=flow_concepts_transaction.htm) - [*Apex Developer Guide*: InvocableMethod Annotation](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm) <!-- document id=65c13b1ede5726d757d55e9ad2a1f0856b7b3e7c04d075bcac4f1c1c00f9b1f0 url=/developer/current/en-us/platform/communities-dev/guides/communities-dev/communities-dev-sample-flow__let-guest-users-create-records.md --> # Sample Flow: Give Guest Users Access to Create Records In this sample flow, the guest user enters feedback and the flow stores it in a custom object record. The guest user doesn’t have access to read the record after creation. **important:** Before you give record creation access to guest users, read [Give Guest Users Access to Create Records](https://developer.salesforce.com/docs/platform/communities-dev/guide/communities-dev-give-guest-users-access-to-create-records.md). ![The sample flow with numbered elements](https://developer.salesforce.com/media/communities-dev/guest_users_flow_create_records.png) ## Custom Feedback__c Object This scenario uses the Feedback__c custom object to store feedback from guest users. A Feedback__c custom object has these fields, listed in alphabetical order: **`Email__c`:** Required. The guest user’s email address. Data type: Email **`Score__c`:** Required. The feedback score entered by the guest user. Possible values are `0`, `1`, `2`, `3`, `4`, `5`. **`Additional_comments__c`:** Any additional feedback entered by the guest user. Data type: Long Text Area ## Flow Configuration Because the flow doesn’t require read access to any records and we’re not relying on object permissions, set the **How to Run the Flow** setting to **System Context without Sharing—Access All Data**. ## Feedback Form (1) The first element in the flow is a screen that displays these components: - An Email component for the user’s email address. - A Slider component for the user’s feedback score, set to allow whole numbers from 0 to 5. - A Long Text Area component for any additional comments. ## Create Records (2) The next element is a Create Records element that creates a Feedback__c record. ## End Screen (3) The final screen element displays text to thank the user for their feedback. **See Also** - [*Salesforce Help*: Which Context Do Flows Run In?](https://help.salesforce.com/articleView?id=flow_distribute_context.htm) - [*Salesforce Help*: Flow Elements](https://help.salesforce.com/articleView?id=flow_ref_elements.htm) - [*Salesforce Help*: Allow Guest Users to Access Flows](https://help.salesforce.com/articleView?id=rss_flow_guestuser.htm) <!-- document id=634e1f62d08ba39c332713ae5aab0bb27067dac59be0266065be85817359f525 url=/developer/current/en-us/platform/api/guides/api/partner/sample-query-calls.md --> # Sample query and queryMore Calls The following Java and C# examples show usage of the [`query()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query.md) and [`queryMore()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-querymore.md) calls for the partner WSDL. Each example sets the batch size of the query to 250 items returned. It then performs a query call to get the first name and last name of all contacts and iterates through the contact records returned. For each contact, it writes the contact’s first name and last name to the output, or only the last name if the first name is null. Finally, if there are more items to be returned by the query, as indicated by a `QueryResult.done` property value of `false`, it calls [`queryMore()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-querymore.md) to get the next batch of items, and repeats the process until no more records are returned. To execute the sample method, you can use the corresponding Java or C# template class provided in [Examples Using the Partner WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-partner-examples.md). ## Java Example <!-- otherprops: java set_clipboard --> ```codesegment public void querySample() { try { // Set query batch size partnerConnection.setQueryOptions(250); // SOQL query to use String soqlQuery = "SELECT FirstName, LastName FROM Contact"; // Make the query call and get the query results QueryResult qr = partnerConnection.query(soqlQuery); boolean done = false; int loopCount = 0; // Loop through the batches of returned results while (!done) { System.out.println("Records in results set " + loopCount++ + " - "); SObject[] records = qr.getRecords(); // Process the query results for (int i = 0; i < records.length; i++) { SObject contact = records[i]; Object firstName = contact.getField("FirstName"); Object lastName = contact.getField("LastName"); if (firstName == null) { System.out.println("Contact " + (i + 1) + ": " + lastName ); } else { System.out.println("Contact " + (i + 1) + ": " + firstName + " " + lastName); } } if (qr.isDone()) { done = true; } else { qr = partnerConnection.queryMore(qr.getQueryLocator()); } } } catch(ConnectionException ce) { ce.printStackTrace(); } System.out.println("\nQuery execution completed."); } ``` ## C# Example <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void querySample() { try { QueryResult qr = null; binding.QueryOptionsValue = new sforce.QueryOptions(); binding.QueryOptionsValue.batchSize = 250; binding.QueryOptionsValue.batchSizeSpecified = true; qr = binding.query("SELECT FirstName, LastName FROM Contact"); bool done = false; int loopCount = 0; while (!done) { Console.WriteLine("\nRecords in results set " + Convert.ToString(loopCount++) + " - "); // Process the query results for (int i = 0; i < qr.records.Length; i++) { sforce.sObject con = qr.records[i]; string fName = con.Any[0].InnerText; string lName = con.Any[1].InnerText; if (fName == null) Console.WriteLine("Contact " + (i + 1) + ": " + lName); else Console.WriteLine("Contact " + (i + 1) + ": " + fName + " " + lName); } if (qr.done) done = true; else qr = binding.queryMore(qr.queryLocator); } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } Console.WriteLine("\nQuery execution completed."); } ``` <!-- document id=fe9146651ae1df6d8c8076b3f7f77415171a528e183a5abc00dcef3318e0822a url=/developer/current/en-us/platform/api/guides/api/partner/sample-search-call.md --> # Sample search Call The following Java and C# examples show how to use the [`search()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-search.md) call for the partner WSDL. Each example accepts a phone number string value that is used in the SOQL query. The search call looks for phone fields that match the passed in phone value in all contacts, leads, and accounts. Next, the example iterates through the returned search results that contain the matching records, adds them to arrays, and writes their field values to the console. The record fields returned correspond to the fields specified in the SOQL query for each record type. To execute the sample method, you can use the corresponding Java or C# template class provided in [Examples Using the Partner WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-partner-examples.md). ## Java Example <!-- otherprops: java set_clipboard --> ```codesegment public void searchSample(String phoneNumber) { try { // Example of phoneNumber format: 4155551212 String soslQuery = "FIND {" + phoneNumber + "} IN Phone FIELDS " + "RETURNING " + "Contact(Id, Phone, FirstName, LastName), " + "Lead(Id, Phone, FirstName, LastName)," + "Account(Id, Phone, Name)"; // Perform SOSL query SearchResult sResult = partnerConnection.search(soslQuery); // Get the records returned by the search result SearchRecord[] records = sResult.getSearchRecords(); // Create lists of objects to hold search result records List<SObject> contacts = new ArrayList<SObject>(); List<SObject> leads = new ArrayList<SObject>(); List<SObject> accounts = new ArrayList<SObject>(); // Iterate through the search result records // and store the records in their corresponding lists // based on record type. if (records != null && records.length > 0) { for (int i = 0; i < records.length; i++){ SObject record = records[i].getRecord(); if (record.getType().toLowerCase().equals("contact")) { contacts.add(record); } else if (record.getType().toLowerCase().equals("lead")){ leads.add(record); } else if (record.getType().toLowerCase().equals("account")) { accounts.add(record); } } // Display the contacts that the search returned if (contacts.size() > 0) { System.out.println("Found " + contacts.size() + " contact(s):"); for (SObject contact : contacts) { System.out.println(contact.getId() + " - " + contact.getField("FirstName") + " " + contact.getField("LastName") + " - " + contact.getField("Phone") ); } } // Display the leads that the search returned if (leads.size() > 0) { System.out.println("Found " + leads.size() + " lead(s):"); for (SObject lead : leads) { System.out.println(lead.getId() + " - " + lead.getField("FirstName") + " " + lead.getField("LastName") + " - " + lead.getField("Phone") ); } } // Display the accounts that the search returned if (accounts.size() > 0) { System.out.println("Found " + accounts.size() + " account(s):"); for (SObject account : accounts) { System.out.println(account.getId() + " - " + account.getField("Name") + " - " + account.getField("Phone") ); } } } else { // The search returned no records System.out.println("No records were found for the search."); } } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## C# Example <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void searchSample(String phoneNumber) { try { // Example of phoneNumber format: 4155551212 String soslQuery = "FIND {" + phoneNumber + "} IN Phone FIELDS " + "RETURNING " + "Contact(Id, Phone, FirstName, LastName), " + "Lead(Id, Phone, FirstName, LastName)," + "Account(Id, Phone, Name)"; // Perform SOSL query SearchResult sResult = binding.search(soslQuery); // Get the records returned by the search result SearchRecord[] records = sResult.searchRecords; // Create lists of objects to hold search result records ArrayList contacts = new System.Collections.ArrayList(); ArrayList leads = new System.Collections.ArrayList(); ArrayList accounts = new System.Collections.ArrayList(); // Iterate through the search result records // and store the records in their corresponding lists // based on record type. if ((records != null) && (records.Length > 0)) { for (int i = 0; i < records.Length; i++) { sObject record = records[i].record; if (record.type.ToLower().Equals("contact")) { contacts.Add(record); } else if (record.type.ToLower().Equals("lead")) { leads.Add(record); } else if (record.type.ToLower().Equals("account")) { accounts.Add(record); } } // Display the contacts that the search returned if (contacts.Count > 0) { Console.WriteLine("Found " + contacts.Count + " contact(s):"); for (int i = 0; i < contacts.Count; i++) { sObject c = (sObject)contacts[i]; Console.WriteLine(c.Any[0].InnerText + " - " + c.Any[2].InnerText + " " + c.Any[3].InnerText + " - " + c.Any[1].InnerText); } } // Display the leads that the search returned if (leads.Count > 0) { Console.WriteLine("Found " + leads.Count + " lead(s):"); for (int i = 0; i < leads.Count; i++) { sObject l = (sObject)leads[i]; Console.WriteLine(l.Any[0].InnerText + " - " + l.Any[2].InnerText + " " + l.Any[3].InnerText + " - " + l.Any[1].InnerText); } } // Display the accounts that the search returned if (accounts.Count > 0) { Console.WriteLine("Found " + accounts.Count + " account(s):"); for (int i = 0; i < accounts.Count; i++) { sObject a = (sObject)accounts[i]; Console.WriteLine(a.Any[0].InnerText + " - " + a.Any[2].InnerText + " - " + a.Any[1].InnerText); } } } else { // The search returned no records Console.WriteLine("No records were found for the search."); } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } } ``` <!-- document id=e1b1d74a3793474db855ab481fb109e3c219abdcff95c99188278e5aaf290648 url=/developer/current/en-us/platform/api/guides/api/partner/sample-update-call.md --> # Sample `update()` Call These Java and C# examples show how to use the `update()` call for the Partner WSDL. Each example takes the ID of the contact to [`update()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-update.md) as an argument. It creates two sObject records of type Contact—one to hold the valid passed in ID and the other has an invalid ID. Next, it sets a new phone number for the valid contact and `null` for the last name of the invalid contact. It then makes the update call and iterates through the results. For a successful update operation, it writes the ID of the contact that got updated. For a failed update operation, it writes the details of all returned errors to the console. In this case, the output is the ID of the contact that was successfully updated and an error for the invalid contact update. To execute the sample method, you can use the corresponding Java or C# template class provided in [Examples Using the Partner WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-partner-examples.md). ## Java Example <!-- otherprops: java set_clipboard --> ```codesegment public void updateSample(String id) { try { // Create an sObject of type contact SObject updateContact = new SObject(); updateContact.setType("Contact"); // Set the ID of the contact to update updateContact.setId(id); // Set the Phone field with a new value updateContact.setField("Phone", "(415) 555-1212"); // Create another contact that will cause an error // because it has an invalid ID. SObject errorContact = new SObject(); errorContact.setType("Contact"); // Set an invalid ID on purpose errorContact.setId("SLFKJLFKJ"); // Set the value of LastName to null errorContact.setFieldsToNull(new String[] {"LastName"}); // Make the update call by passing an array containing // the two objects. SaveResult[] saveResults = partnerConnection.update( new SObject[] {updateContact, errorContact} ); // Iterate through the results and write the ID of // the updated contacts to the console, in this case one contact. // If the result is not successful, write the errors // to the console. In this case, one item failed to update. for (int j = 0; j < saveResults.length; j++) { System.out.println("\nItem: " + j); if (saveResults[j].isSuccess()) { System.out.println("Contact with an ID of " + saveResults[j].getId() + " was updated."); } else { // There were errors during the update call, // go through the errors array and write // them to the console. for (int i = 0; i < saveResults[j].getErrors().length; i++) { Error err = saveResults[j].getErrors()[i]; System.out.println("Errors were found on item " + j); System.out.println("Error code: " + err.getStatusCode().toString()); System.out.println("Error message: " + err.getMessage()); } } } } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` For more information about `setFieldsToNull` (or its equivalent in client tools other than WSC), see [`fieldsToNull`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md). ## C# Example <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void updateSample(String id) { try { // Create an sObject of type contact sObject updateContact = new sObject(); updateContact.type = "Contact"; // Set the ID of the contact to update updateContact.Id = id; // Set the Phone field to a new value. // The Phone field needs to be created as an XML element. System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement phoneField = doc.CreateElement("Phone"); phoneField.InnerText = "(415) 555-1212"; // Add the Phone field to the contact updateContact.Any = new System.Xml.XmlElement[] {phoneField}; // Create another contact that will cause an error // because it has an invalid ID. sObject errorContact = new sObject(); errorContact.type = "Contact"; // Set an invalid ID on purpose errorContact.Id = "SLFKJLFKJ"; // Set the value of LastName to null errorContact.fieldsToNull = new String[] { "LastName" }; // Make the update call by passing an array containing // the two objects. SaveResult[] saveResults = binding.update( new sObject[] {updateContact, errorContact}); // Iterate through the results and write the ID of // the updated contacts to the console, in this case one contact. // If the result is not successful, write the errors // to the console. In this case, one item failed to update. for (int j = 0; j < saveResults.Length; j++) { Console.WriteLine("\nItem: " + j); if (saveResults[j].success) { Console.WriteLine("Contact with an ID of " + saveResults[j].id + " was updated."); } else { // There were errors during the update call, // go through the errors array and write // them to the console. for (int i = 0; i < saveResults[j].errors.Length; i++) { Error err = saveResults[j].errors[i]; Console.WriteLine("Errors were found on item " + j.ToString()); Console.WriteLine("Error code: " + err.statusCode.ToString()); Console.WriteLine("Error message: " + err.message); } } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } } ``` <!-- document id=119f2826b8b5c69615f85dce7ce20eb83951f4804eb19eea4eca891f0507f2d5 url=/developer/current/en-us/platform/ajax/guides/ajax/sforce-api-ajax-vf-sample.md --> # Sample Visualforce Page Using the AJAX Toolkit This example demonstrates using the AJAX Toolkit in a Visualforce page. To add JavaScript to a Visualforce page, use this procedure: 1. Create the Visualforce page. For more information, see the *[Visualforce Developer's Guide](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/)*. 2. Cut and paste the following sample code into your Visualforce page. The JavaScript code queries your organization and returns every account ID, account name, and industry type, if any: <!-- otherprops: set_clipboard --> ```html <apex:page > <script type="text/javascript"> var __sfdcSessionId = '{!GETSESSIONID()}'; </script> <script src="../../soap/ajax/68.0/connection.js" type="text/javascript"></script> <script type="text/javascript"> window.onload = setupPage; function setupPage() { //function contains all code to execute after page is rendered var state = { //state that you need when the callback is called output : document.getElementById("output"), startTime : new Date().getTime()}; var callback = { //call layoutResult if the request is successful onSuccess: layoutResults, //call queryFailed if the api request fails onFailure: queryFailed, source: state}; sforce.connection.query( "Select Id, Name, Industry From Account order by Industry", callback); } function queryFailed(error, source) { source.output.innerHTML = "An error has occurred: " + error; } /** * This method will be called when the toolkit receives a successful * response from the server. * @queryResult - result that server returned * @source - state passed into the query method call. */ function layoutResults(queryResult, source) { if (queryResult.size > 0) { var output = ""; //get the records array var records = queryResult.getArray('records'); //loop through the records and construct html string for (var i = 0; i < records.length; i++) { var account = records[i]; output += account.Id + " " + account.Name + " [Industry - " + account.Industry + "]<br>"; } //render the generated html string source.output.innerHTML = output; } } </script> <div id="output"> </div> </apex:page> ``` After you created and navigated to the Visualforce page, you see text similar to this image: ![output of scontrol, list of Ids, names, and value for industry](https://developer.salesforce.com/media/ajax/scontrol_output.gif) **note:** You can also use an Apex controller to create the Visualforce page. However, this sample is about basic functionality with the AJAX Toolkit that contains API calls and processes Salesforce data. <!-- document id=fe3625f1be68eb46ece4057b76f2a85f928a2eeed85759062f8f1162034a26e6 url=/developer/current/en-us/platform/aura-platform/guides/aura/data-service/data-service-saverecordresult.md --> # SaveRecordResult Represents the result of a Lightning Data Service operation that makes a persistent change to record data. ## `SaveRecordResult` Object Callback functions for the `saveRecord` and `deleteRecord` functions receive a `SaveRecordResult` object as their only argument. |Attribute Name|Type|Description| |--------------|----|-----------| |`objectApiName`|String|The object API name for the record.| |`entityLabel`|String|The label for the name of the sObject of the record.| |`error`|String|A localized message indicating what went wrong, or an array of errors that includes a localized message and might also include further data to help handle the error, such as field- or page-level errors. `error` is undefined if the save `state` is SUCCESS or DRAFT.| |`recordId`|String|The 18-character ID of the record affected.| |`state`|String|The result state of the operation. Possible values are SUCCESS (the operation completed on the server successfully), DRAFT (the server wasn’t reachable, so the operation was saved locally as a draft and is applied to the server when it’s reachable), INCOMPLETE (the server wasn’t reachable, and the device doesn’t support drafts, which are supported only in the Salesforce app; try this operation again later), or ERROR (the operation couldn’t be completed; check the `error` attribute for more information).| <!-- document id=af1e3410762bd75247911fcf7d89fb52da4f53f4058e36d436d9cb8a2f4d2925 url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-create-saveresult.md --> # SaveResult The `create()` call returns an array of SaveResult objects. Each element in the SaveResult array corresponds to the [sObject](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject)[] array passed as the [`sObjects`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-create.md) parameter in the [`create()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-create.md) call. For example, the object returned in the first index in the SaveResult array matches the object specified in the first index of the sObject[] array. A SaveResult object has these properties. |Name|Type|Description| |----|----|-----------| |`id`|ID|ID of the [sObject](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject) that you attempted to [`create()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-create.md). If this field contains a value, then the object was created successfully. If this field is empty, then the object wasn’t created and the API returned error information instead.| |`success`|boolean|Indicates whether the [`create()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-create.md) call succeeded (`true`) or not (`false`) for this object.| |`errors`|Error[]|If an error occurred during the [`create()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-create.md) call, an array of one or more [Error](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#error) objects providing the error code and description. If your organization has active duplicate rules and a duplicate is detected, the SaveResult includes an Error with a data type of [DuplicateError](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_duplicateerror.htm).| <!-- document id=18dadcdaff78f104ef7f82dbab4532af9641fb580970eb47361f45118c78bc6a url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-update-saveresult.md --> # SaveResult The `update()` call returns an array of SaveResult objects. Each element in the SaveResult array corresponds to the [sObject](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject)[] array passed as the `sObjects` parameter in the `update()` call. For example, the object returned in the first index in the SaveResult array matches the object specified in the first index of the sObject[] array. A SaveResult object has these properties. |Name|Type|Description| |----|----|-----------| |`id`|ID|ID of an sObject that you successfully updated. If this field contains a value, then the object was updated successfully. If this field is empty, then the object wasn’t updated and the API returned error information instead.| |`success`|boolean|Indicates whether the `update()` call succeeded (`true`) or not (`false`) for this object.| |`errors`|Error[]|If an error occurred during the `update()` call, an array of one or more [Error](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#error) objects providing the error code and description. If your organization has active duplicate rules and a duplicate is detected, the SaveResult includes an Error with a data type of [DuplicateError](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_duplicateerror.htm).| <!-- document id=5285614691d2d0ec462dd55e27507d51fb7c97d18bd737a949522772f212ff64 url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/capabilities/barcodescanner/use-barcodescanner.md --> # Scan Barcodes on a Mobile Device A Lightning web component can use a mobile device’s camera and mobile OS platform features to scan a barcode, such as a UPC symbol or QR code. When a barcode is successfully scanned, the data that was read from the barcode is returned to the Lightning web component that invoked it. Scanning is performed locally on the mobile device, and doesn’t need a network connection. BarcodeScanner does require access to platform-specific APIs that are available only within compatible Salesforce mobile apps. **important:** BarcodeScanner does not and cannot function when running in a web browser, whether running on a desktop or mobile device. BarcodeScanner provides to your component a string value of the data encoded in a scanned barcode. It doesn't attempt to interpret or process the decoded value. - **[Barcode Scanning User Experience](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-intro.md)** Your component can deliver any user experience you desire, but there’s a common flow for any component that can scan a barcode. - **[Use the BarcodeScanner API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-in-a-lightning-component.md)** To develop a Lightning component with barcode scanning features, use the BarcodeScanner API. - **[BarcodeScanner Example–Modern Scanning API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-modern.md)** Here’s a complete example of a Lightning web component that uses BarcodeScanner to scan multiple barcodes simultaneously and process them in a batch after scanning is completed. - **[BarcodeScanner Example—Single Scan (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example.md)** Here’s a minimal but complete example of a Lightning web component that uses BarcodeScanner to recognize a barcode. - **[Scan Multiple Barcodes (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-scan-multiple-barcodes.md)** To scan multiple barcodes in a single scanning session, use `resumeCapture()` to create a continuous scanning cycle that scans barcodes until the user clicks the **Cancel** button. - **[BarcodeScanner Example—Continuous Scanning (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-continuous.md)** Here’s a minimal but complete example of a Lightning web component that uses BarcodeScanner to scan for and recognize multiple barcodes in a continuous cycle. - **[Create a Self-Service Kiosk Application](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-create-self-service-application.md)** Use BarcodeScanner with a device’s front-facing camera to create applications suitable for use as an unattended self-service kiosk. - **[BarcodeScanner Example—Self-Service Kiosk (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-kiosk.md)** Here’s a complete example of a Lightning web component with BarcodeScanner that could serve as a self-service kiosk. - **[Customize the BarcodeScanner User Interface](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-ui.md)** BarcodeScanner provides a standard, minimal user interface that can be used out of the box. For applications and use cases where the standard user interface doesn’t provide enough information, or to customize for your company or brand, create a custom UI using HTML. - **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-compatibility.md)** BarcodeScanner 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 BarcodeScanner runs within a compatible Salesforce mobile app. **It does not and cannot function when running in a 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-barcodescanner-considerations.md)** Keep the following in mind when developing features that use the BarcodeScanner API. **See Also** - [_Lightning Web Components Developer Guide:_ BarcodeScanner API](https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-barcodescanner.html) <!-- document id=12efaf0f3062e22c824903bb36fdcba9c9a5eb065d8d8e908e920672c9c2da6e url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/capabilities/documentscanner/use-documentscanner.md --> # Scan Documents on a Mobile Device A Lightning web component can use a device’s camera and optical character recognition (OCR) to scan documents. When a document is successfully scanned, text data extracted from the scanned document is returned to the Lightning web component that invoked it. DocumentScanner recognizes printed text and handwritten form factors. However, DocumentScanner provides the most accurate results when scanning printed text compared handwritten text, which varies on the legibility of handwritten characters. DocumentScanner results are returned in two formats: - A simple string of all recognized text, suitable for simple document capture. - Structured text data aligned with the scanned image, suitable for interactive processing of document content. Scanning is performed locally on the mobile device, and doesn't need a network connection. However, DocumentScanner requires access to APIs implemented in platform-native code that are available only within compatible Salesforce mobile apps. **important:** DocumentScanner does not and cannot function when running in a web browser, whether on a desktop or mobile device. - **[Use the DocumentScanner API](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-documentscanner-in-a-lightning-component.md)** To add document scanning features to a Lightning web component, use the DocumentScanner API. - **[DocumentScanner Example](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-documentscanner-example.md)** Here’s an example of a Lightning web component that uses DocumentScanner to capture text data from an image. - **[Compatibility and Requirements](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-documentscanner-compatibility.md)** DocumentScanner 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 DocumentScanner 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-documentscanner-considerations.md)** Consider these guidelines and limitations when developing features that use the DocumentScanner API. <!-- document id=b3ed94fcf88bd58a31d69d7cfbb3a4b4c5bde99cfceea003a06edfebb4888b89 url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/capabilities/barcodescanner/use-barcodescanner-scan-multiple-barcodes.md --> # Scan Multiple Barcodes (Legacy) To scan multiple barcodes in a single scanning session, use `resumeCapture()` to create a continuous scanning cycle that scans barcodes until the user clicks the **Cancel** button. **important:** We recommend using the modern `scan()` and `dismiss()` API functions in your LWC scanning code to streamline your development experience. The legacy API functions `beginCapture()`, `resumeCapture()`, and `endCapture()` are still available, but will be retired in a future release. See [Understand BarcodeScanner Modern and Legacy APIs](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-scan-barcodes.md) for additional details. Sometimes you want to scan many barcodes in a row, without requiring user interaction between scans. For example, when scanning a shelf of inventory, you might not want to stop after each item, or to click a **Scan** button for every item. In these cases, it can make more sense to click **Scan** once, and then scan barcodes repeatedly until done with all of the items. Implementing a continuous scanning cycle like this is slightly different from scanning a single item. 1. Start a scanning session as usual, with `beginCapture()`. 2. When the promise resolves, process the scanned barcode as usual, in the `then()` block. **note:** Processing the barcode can’t change the user interface, or require interacting with the user. That needs to wait until _after_ the scanning cycle completes. 3. At the end of the `then()` block, call a new continue scanning function, which uses `resumeCapture()` to continue the current scanning session. 4. Call `endCapture()` at the end of the `catch()` block, instead of in the `finally()` block. 5. When the user clicks **Cancel** to end the scanning session, `BarcodeScanner` returns a `BarcodeScannerError` object with a `code` property value of `userDismissedScanner`. Handle cancellation and actual errors in the `catch()` block. ## Single Scan vs. Continuous Scan The core scanning lifecycles for single scans and continuous scanning are similar, but different enough that it’s worth comparing the two. **Single Scan** ```javascript singleScanner .beginCapture(scanningOptions) .then((scannedBarcode) => this.processScannedBarcode(scannedBarcode)) .catch((error) => { console.error(error); }) .finally(() => { singleScanner.endCapture(); }); ``` **Continuous Scan** ```javascript sessionScanner.beginCapture(scanningOptions) .then((scannedBarcode) => this.processScannedBarcode(scannedBarcode) this.continueScanning(); ) .catch((error) => { console.error(error); sessionScanner.endCapture(); }); ``` There are two significant differences to note. - The continuous scanning `then()` block has a call to a new function, `continueScanning()`. See the **Continue a Scanning Session** section. - The call to `endCapture()` is made in the `finally()` block for the single scan, but is called in the `catch()` error handling block for continuous scanning. See the **End Capture for Continuous Scanning** section. ## Continue a Scanning Session In the preceding code comparison, the technique of continuing a scanning session was hidden behind the new line, a call to `continueScanning()`. Here’s an example of that function. ```javascript continueScanning() { this.sessionScanner.resumeCapture() .then((scannedBarcode) => { this.processScannedBarcode(scannedBarcode); this.continueScanning(); }) .catch((error) => { this.processError(error); this.sessionScanner.endCapture(); }); } ``` This code should look familiar; it’s nearly identical to the earlier `beginCapture()` example for continuous scanning. There‘s only one difference: `continueScanning()` creates a promise chain by calling `sessionScanner.resumeCapture()`, while the earlier example called `sessionScanner.beginCapture()`. It might be obvious, but you only call `beginCapture()` _once,_ at the beginning of a scanning cycle. While the difference in the code is minor, the difference in the flow of execution is significant. The scanning cycle begins in a promise chain created by `beginCapture()`, which executes **only once.** That initial promise resolves one of two ways: - If the scan is successful, the barcode result is processed, and then the flow of control for the scanning cycle is handed off to `continueScanning()`. - If the user clicks **Cancel**, or if there’s an error, the promise chain ends in the `catch()` error handling block, covered in the **End Capture for Continuous Scanning** section. The promise chain in `continueScanning()` ends the same two ways, with one important difference. While the code is the same, after a successful scan it continues the scanning cycle by calling _itself_, creating a recursive loop that continues the scanning cycle until the user clicks **Cancel**, or there’s an error. Whoops. Didn’t mean to scare you with that word, recursive. Yes, `continueScanning()` ends by calling itself, which makes it a recursive function. But this recursion is pretty simple—it’s just a loop, an event loop of sorts. The loop handles _scan-something_ events (in the `then()` block) until a _user-clicked-Cancel_ event comes along (in the `catch()` block), and then it ends. It might take a minute, but you can wrap your head around it. The overall pattern here is the following: - You begin a scanning cycle using `beginCapture()`. - The promise resolution chain from `beginCapture()` ends in a call to `continueScanning()`, your own function. - `continueScanning()` continues the existing scanning cycle by calling `resumeCapture()`, but is otherwise the same as the `beginCapture()` that started the cycle. - The promise resolution chain in `continueScanning()` ends in a call to `continueScanning()`, creating a scanning cycle loop. - The loop ends when the user clicks **Cancel**, `BarcodeScanner` rejects the promise with a `BarcodeScannerError`, and you call `endCapture()` in the error handling `catch()` block. The code duplication between the `beginCapture()` and `resumeCapture()` promise chains is unfortunate, but unavoidable. Move as much processing code, such as the handling of a scanned barcode, into functions you can call from both chains. In the example here, `processScannedBarcode()` is a function that both promise chains use to handle a successful scan. See [BarcodeScanner Example—Continuous Scanning (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-continuous.md) for the complete sample, which includes that function’s implementation. ## End Capture for Continuous Scanning In a continuous scanning session, the user scans items repeatedly until they’re out of items. Then they click the **Cancel** button to end the session. In code, `BarcodeScanner` handles cancellation by rejecting the promise, and returning a `BarcodeScannerError` to signal that the user canceled scanning. See [BarcodeScanner Example—Continuous Scanning (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-continuous.md) for how to distinguish between the user clicking **Cancel** and an actual error. Importantly, clicking the **Cancel** button is the only way to end a continuous scanning session. This is in contrast to a single scan session, which can end with either a successful scan _or_ the **Cancel** button. Because continuous scanning always ends with the **Cancel** button, and thus a `BarcodeScannerError`, we can call `endCapture()` in the error handling `catch()` block. However, because a single scan might _not_ end in a `BarcodeScannerError`, the `catch()` block might never execute. So for a single scan, we put `endCapture()` in the `finally()` block, to make sure that, success or failure, it always gets called. **See Also** - [BarcodeScanner Example—Continuous Scanning (Legacy)](https://developer.salesforce.com/docs/platform/mobile-offline/guide/use-barcodescanner-example-continuous.md) <!-- document id=da28e6566dead3baa7aba537ff8fbaf2c7402226681ecbac289fcace05998879 url=/developer/current/en-us/platform/api-rest/guides/resources/requests-ls-scheduling.md --> # Scheduling Returns a list of available Salesforce Scheduler REST resources and corresponding URIs. This resource is available in REST API version 45.0 and later. ## Syntax **URI:** `/services/data/vXX.X/scheduling/` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` ## Example **Example Response Body** ```nolang { "getAppointmentCandidates" : "/services/data/v68.0/scheduling/getAppointmentCandidates", "getAppointmentSlots" : "/services/data/v68.0/scheduling/getAppointmentSlots" } ``` <!-- document id=110bad7b2fb55d53801ab6c6862b4295438251b73b8dbb116f54e34c3d68a2fc url=/developer/current/en-us/platform/api-asynch/guides/api-asynch/asynch-api-reference-schema.md --> # Schema The Bulk API service is described by an XML Schema Document (XSD) file. You can download the schema file for an API version by using this URI: **Web_Services_SOAP_endpoint_hostname**`/services/async/`**APIversion**/AsyncApi.xsd For example, if you're working with version 68.0 of the Bulk API, the URI for a production org is in this format. `https://MyDomainName.my.salesforce.com/services/async/68.0/AsyncApi.xsd` You can find the My Domain name and My Domain login URL for your org on the My Domain page in Setup. Or, to get the hostname of your My Domain login URL in Apex, use the `getMyDomainHostname()` method of the `System.DomainCreator` class. ## Schema and API Versions The schema file is available for API versions earlier than the current release. You can download the schema file for API version 18.0 and later. For example, if you want to download the schema file for API version 31.0, use this URI: `https://MyDomainName.my.salesforce.com/services/async/31.0/AsyncApi.xsd` **See Also** - [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-reference-jobinfo.md) - [BatchInfo](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-reference-batchinfo.md) - [Errors](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-reference-errors.md) <!-- document id=6ff45ce4be76424e1e5f375431f4d1027608801eb040f172eacec8a2d2689811 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/javascript/pages-js-remoting-scope-visibility.md --> # Scope and Visibility of @RemoteAction Methods Apex `@RemoteAction` methods must be `static` and either `global` or `public`. Don’t use globally exposed remote actions to perform sensitive operations or to expose nonpublic data. `Global` remote actions can only call other `global` methods. You can’t use public remote actions in `global` components, or in a `global` scope. Scope escalation results in a compiler error, or for references that are resolved at runtime, a runtime failure. This table describes the restrictions. | `@RemoteAction` Scope | Visualforce Page | Non-Global Component | Global Component | iframe | Access Across Packages | | --------------------- | ---------------- | -------------------- | ---------------- | ------- | ------------------------------------------------------------------------------------------ | | Global Remote Method | Allowed | Allowed | Allowed | Allowed | Allowed | | Public Remote Method | Allowed | Allowed | Error | Error | Packages must share the namespace. Method must have the `@namespaceAccessible` annotation. | **note:** If a @RemoteAction method is in a managed package and used by Visualforce Remoting, it must have global visibility if user profile or permission set access is used. When remote actions are accessed via markup they are included indirectly via components, the `<apex:include>,` or the `<apex:composition>` tags. The scope of the remote method is carried forward into the top-level container (the top-level item in the inclusion hierarchy), which must abide by scope escalation rules. | @RemoteAction Accessed From | Visualforce Page | Non-Global Component | Global Component | iframe | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | Global Component | Allowed | Allowed | Allowed | Allowed | | Non-Global Component | Allowed | Allowed | Allowed only if non-global component doesn't include public remote methods. | Allowed only if non-global component doesn't include public remote methods. | | `<apex:include>` `<apex:composition>` | Allowed within the same namespace; error if namespaces are different and the included page or its child hierarchy contains public remote methods. | n/a | n/a | Error | <!-- document id=92fe2cbe33e21b34b078b11b23ac96d1e4521772d380b8cbab8efcaee8922eb4 url=/developer/current/en-us/platform/api/guides/api/guidelines/scope-of-data-replication.md --> # Scope of Data Replication This feature provides a mechanism that targets data replication (one-way copying of data). It does not provide data synchronization (two-way copying of data) or data mirroring capabilities. <!-- document id=db2bcd9b539a9f0032683ae14af8373b3b2950c0c96540e8ecf075871d2f9bfc url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search.md --> # Search Executes the specified SOSL search. The search string must be URL-encoded. For more information on SOSL see the [SOQL and SOSL Reference](http://www.salesforce.com/us/developer/docs/soql_sosl/index_Left.htm). ## Syntax **URI:** `/services/data/vXX.X/search/?q=SOSL_searchString` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`q`|A SOSL statement that is properly URL-encoded.| ## Example See [Search for a String](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-search.md). <!-- document id=38a64109ce2b3fc75ac748fa9f456ba04438528dc9e6d147d7768d947ae2a6ba url=/developer/current/en-us/platform/salesforce-large-data-volumes-bp/guides/cce/ldv-deployments/ldv-deployments-techniques-search.md --> # Search When large volumes of data are added or changed, the search system must index that information before it becomes available for search by all users, and this process might take a long time. See [Search Architecture](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-concepts-search-architecture.md). <!-- document id=6dfb01e704fa09a7b3bcb5da67845994547d53b0421439b0374ce30234d7ddee url=/developer/current/en-us/platform/salesforce-large-data-volumes-bp/guides/cce/ldv-deployments/ldv-deployments-concepts-search-architecture.md --> # Search Architecture *Search* is the capability to query records based on free-form text. The Salesforce search architecture is based on its own data store, which is optimized for searching for that text. Salesforce provides search capabilities in many areas of the application, including: - The sidebar - Advanced and global searches - Find boxes and lookup fields - Suggested Solutions and Knowledge Base - Web-to-Lead and Web-to-Case - Duplicate lead processing - Salesforce Object Search Language (SOSL) for Apex and the API For data to be searched, it must first be indexed. The indexes are created using the search indexing servers, which also generate and asynchronously process queue entries of newly created or modified data. After a searchable object’s record is created or updated, it could take about 15 minutes or more for the updated text to become searchable. Salesforce performs indexed searches by first searching the indexes for appropriate records, then narrowing down the results based on access permissions, search limits, and other filters. This process creates a *result set*, which typically contains the most relevant results. After the result set reaches a predetermined size, the remaining records are discarded. The result set is then used to query the records from the database to retrieve the fields that a user sees. **tip:** Search can also be accessed with SOSL, which in turn can be invoked using the API or Apex. <!-- document id=b2799d0927710ad5001eadee605ea6d10dd1e07a6494c31e9c3694774022b19c url=/developer/current/en-us/platform/api-rest/guides/do-me/dome-search.md --> # Search for a String Use the Search resource to execute a SOSL search or use the Parameterized Search resource to execute a simple RESTful search without SOSL. ## Example SOSL Search Using the GET Method The following example executes a SOSL search for `Acme`. The search string in this example must be URL-encoded. **Example usage** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/search/?q=FIND+%7BAcme%7D -H "Authorization: Bearer token" ``` **Example request body:** None required **Example response body** ```nolang { "searchRecords" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IqhSLIAZ" }, "Id" : "001D000000IqhSLIAZ", }, { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IomazIAB" }, "Id" : "001D000000IomazIAB", } ] } ``` ## Example Parameterized Search Using the GET Method The following example executes a parameterized search for `Acme`. The search string in this example must be URL-encoded. **Example usages** **Global search for all results containing *Acme*** **Account search for results containing *Acme*, returning the id and name fields** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/parameterizedSearch/?q=Acme -H "Authorization: Bearer token" ``` ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/parameterizedSearch/?q=Acme&sobject=Account&Account.fields=id,name&Account.limit=10 -H "Authorization: Bearer token" ``` **Example request body:** None required **Example response body** ```nolang { "searchRecords" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IqhSLIAZ" }, "Id" : "001D000000IqhSLIAZ" }, { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IomazIAB" }, "Id" : "001D000000IomazIAB" } ] } ``` **Example response body with `metadata` parameter** **note:** The `metadata` parameter is only returned if the request specified `metadata=LABELS`. ```nolang { "searchRecords" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IqhSLIAZ" }, "Id" : "001D000000IqhSLIAZ", }, { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IomazIAB" }, "Id" : "001D000000IomazIAB", } ], "metadata" : { "entityetadata" : [ { "entityName" : "Account", "fieldMetadata" : [ { "name" : "Name", "label" : "Account Name" } ] } ] } } ``` ## Example Parameterized Search Using the POST Method Execute a parameterized search using the POST method to access all search features available. **Example usage** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/parameterizedSearch "Authorization: Bearer token" -H "Content-Type: application/json” -d "@search.json” ``` **Example request body:** None required **Example JSON file** ```nolang { "q":"Smith", "fields" : ["id", "firstName", "lastName"], "sobjects":[{"fields":["id", "NumberOfEmployees"], "name": "Account", "limit":20}, {"name": "Contact"}], "in":"ALL", "overallLimit":100, "defaultLimit":10 } ``` **Example response body** ```nolang { "searchRecords" : [ { "attributes" : { "type" : "Contact", "url" : "/services/data/v68.0/sobjects/Contact/003xx000004TraiAAC" }, "Id" : "003xx000004TraiAAC", "FirstName" : "Smith", "LastName" : "Johnson" }, { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DHXnAAO" }, "Id" : "001xx000003DHXnAAO", "NumberOfEmployees" : 100 } ] } ``` **See Also** - [Search](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-search.md) - [Parameterized Search](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-search-parameterized.md) <!-- document id=e5b0f1292d5a2ba8a4a6df0ab839b2368262e34142d8f0623700f20db09161cd url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-suggest-records.md --> # Search for Records Suggested by Autocomplete and Instant Results Returns a list of suggested records whose names match the user’s search string. The suggestions resource provides autocomplete results and instant results for users to navigate directly to likely relevant records, before performing a full search. This resource is available in REST API version 32.0 and later. The suggestions resource returns records when the record’s name field includes the exact text in the search string. The last term in the search string can match the beginning of a word. Records that contain the search string within a word aren’t considered a match. **note:** If the user’s search query contains quotation marks or wildcards, those symbols are automatically removed from the query string in the URI. For example, the text string `national u` is treated as `national u*` and returns “National Utility”, “National Urban Company”, and “First National University”. The suggestions resource returns display-ready data about likely relevant records that the user can access. A relevance algorithm determines the order of results. Each suggested record in the results contains these elements: |Element|Description| |-------|-----------| |`Attributes`|The record’s object type and the URL for accessing the record. Also includes the requested lookup fields’ values. For example, if you requested `fields=Id,Name`, the result would include the ID and name.| |`Name` (or `Title`)|The record’s Name field. In the absence of a standard Name field, the Title field is used for these objects: Dashboard, Idea, IdeaTheme, Note, or Question. In the absence of a standard Name or Title field, the main identifying field is used. For example, in cases, the Case Number is used.| |`Id`|The record’s unique identifier.| The suggestions resource supports all searchable objects except the following. - ContentNote - Event - External objects - FeedComment - FeedPost - IdeaComment - Pricebook2 - Reply - TagDefinition - Task ## Syntax **URI:** `/services/data/vXX.X/search/suggestions?q=searchString&sobject=objectTypes` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None required **Request parameters** |Parameter|Description| |---------|-----------| |`fields`|Optional. Used for creating lookup queries. Specify multiple fields using a comma-separated list. Specifies which lookup fields to be returned in the response.| |`dynamicFields`|Optional. Available in API version 48.0 and later. Used to return additional dynamic fields. Specify multiple options using a comma-separated list. For example, if `dynamicFields=secondaryField` then each suggested record in the results contains an additional field besides `Id` and `Name` (or `Title`) based on the next eligible field in the search layout.| |`groupId`|Optional. Specifies one or more unique identifiers of one or more groups that the question to return was posted to. Specify multiple groups using a comma-separated list. This parameter is only applicable when the parameter type equals `question`. Don’t use with the `userId`.| |`ignoreUnsupportedSObjects`|Optional. If an unsupported object is included in a request, this parameter indicates what action to take. If it’s set to `false`, an error is returned. If it’s set to `true`, the object is ignored and no error is returned. See the Unsupported Objects section for reference. The default is `false`.| |`limit`|Optional. Specifies the maximum number of suggested records to return. If a limit isn’t specified, 5 records are returned by default. If there are more suggested records than the limit specified, the response body’s `hasMoreResults` property is `true`.| |`networkId`|Optional. Specifies one or more unique identifiers for the Experience Cloud sites to return the question to. Specify multiple sites using a comma-separated list. This parameter is only applicable when the parameter `type` equals `question` or parameter `sobject` equals `user`.| |`q`|Required. The user’s search query string, properly URL-encoded. Suggestions are returned only if the user’s query string meets the minimum length requirements: one character for queries in Chinese, Japanese, Korean, and Thai; three characters for all other languages. Query strings that exceed the maximum length of 255 characters (or 200 consecutive characters without a space break) return an error.| |`sobject`|Required. The objects that the search is scoped to, such as Account or offer__c. If the `sobject` value is `feedItem`, the `type` parameter is required and it must have a value of `question`. Specify up to 10 objects with a comma-separated list. For example: `sobject=Account,Contact,Lead`. To take advantage of the feature, activate the **CrossObjectTypeahead** permission. To specify the specific fields to return by object, use the following syntax with multiple fields in a comma-separated list. The sobject is lowercase: `sobject=sobject.fields=fields`.| |`topicId`|Optional. Specifies the unique identifier of the single topic that the question to return was tagged as. This parameter is only applicable when the parameter `type` equals `question`.| |`type`|Required when the `sobject` value is `feedItem`. Including this parameter for all other `sobject` values doesn’t affect the query. Specifies that the type of Feed is questions. Valid value: `question`.| |`userId`|Optional. Specifies one or more unique identifiers of one or more users who authored the question to return. Specify multiple users using a comma-separated list. This parameter is only applicable when the parameter type equals `question`. Don’t use with the `groupId`.| |`useSearchScope`|Optional. Available in API version 40.0 and later. The default value is `false`. If `false`, the objects specified in the request are used to suggest records. If `true`, in addition to the objects specified in the request, the user's search scope is used to suggest records. The search scope is the list of objects a user uses most frequently. If the request doesn’t specify an object, use `useSearchScope=true`. If `useSearchScope=true` and the user's search scope is empty, the default search scope is used to suggest records. Typically, only the first 10 objects are used to suggest records. However, an admin can assign objects that are always considered when returning results. If configured, up to 15 objects are used to suggest records. For more information about assigning objects, see [Assign Search Results Objects to Users (Beta)](https://help.salesforce.com/s/articleView?id=ai.search_ai_assign_result_objs.htm&type=5). Objects specified in the `sobject` parameter are prioritized over objects in the user's search scope. Values for the `ignoreUnsupportedSObjects` parameter aren’t applied to the objects in the search scope.| |`where`|Optional. A filter that follows the same syntax as the SOQL `WHERE` clause. URLs encode the expression. Use the clause for an object, or globally for all compatible objects. An example of an object-specific clause is: `account.where=name%20LIKE%20%27Smith%25%27`. An example of a global clause is: `where=name%20LIKE%20%27Smith%25%27`. The parameter must be lower case. Any object-specific `where` clauses override the global `where` clause. You can’t use this parameter for the Question object. To specify multiple entities, see the following example. This feature is available in version 38.0 and later.| Example `sobject` fields: ```nolang &sobject=Account,Contact,Lead&account.fields=Website,Phone &contact.fields=Phone ``` Example using only the search scope: ```nolang .../search/suggestions?q=Acme&useSearchScope=true ``` Example using the search scope and the Account object: ```nolang .../search/suggestions?q=Acme&sobject=Account&useSearchScope=true ``` Example `where` with multiple entities: ```nolang ...search/suggestions?q=Smith &sobject=Account,Contact,KnowledgeArticleVersion,CollaborationGroup,Topic,FeedItem // Specifies a global where clause (to filter Account and Contact) &where=name%20LIKE%20%27Smith%25%27 // Overrides the global where clause for Knowledge Article (filtering by PublishStatus and Language is required for KnowledgeArticle) &knowledgearticleversion.where=PublishStatus='online'+and+language='en_US' // Overrides the global where clause for Topic &topic.where=networkid=<1234567891> // Overrides the global where clause for CollaborationGroup &collaborationgroup.where=networkid=<1234567891> // FeedItem-Question doesn't support where clauses, but we can filter the type and networkId&type=question &networkId==<1234567891> ``` ## Example **Example Response Body** ```nolang { "autoSuggestResults" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DH6WAAW" }, "Id" : "001xx000003DH6WAAW", "Name" : "National Utility Service" }, { { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DHJ4AAO" }, "Id" : "001xx000003DHJ4AAO", "Name" : "National Utility Service" }, { { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DHscAAG" }, "Id" : "001xx000003DHscAAG", "Name" : "National Urban Technology Center" } ], "hasMoreResults" : false, "meta" : { "nameFields" : [ { "entityApiName" : "Account", "fieldApiName" : "Name" } ], "secondaryFields" : [ ] } } ``` **Example Response Body for a Multiple Object Request** ```nolang { "autoSuggestResults" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DMEKAA4" }, "Id" : "001xx000003DMEKAA4" "Name" : "Joe Doe Printing" }, { { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001xx000003DLjvAAG" }, "Id" : "001xx000003DLjvAAGO" "Name" : "Joe Doe Plumbing" }, { { "attributes" : { "type" : "Contact", "url" : "/services/data/v68.0/sobjects/Contact/003xx000004U9Y9AAK" }, "Id" : "003xx000004U9Y9AAK" "Name" : "John Doe" } ], "hasMoreResults" : false, "meta" : { "nameFields" : [ { "entityApiName" : "Account", "fieldApiName" : "Name" }, { "entityApiName" : "Contact", "fieldApiName" : "Name" } ], "secondaryFields" : [ ] } } ``` **Example XML Response Body** ```nolang <?xml version=”1.0” encoding=”UTF-8”? <suggestions> <autoSuggestResults type="Account" url="/services/data/v68.0/sobjects/Account/001xx000003DH6WAAW"> <Id>001xx000003DH6WAAW</Id> <Name>National Utility Service</Name> </autoSuggestResults> <autoSuggestResults type="Account" url="/services/data/v68.0/sobjects/Account/001xx000003DHJ4AAO"> <Id>001xx000003DHJ4AAO</Id> <Name>National Utility Service</Name> </autoSuggestResults> <autoSuggestResults type="Account" url="/services/data/v68.0/sobjects/Account/001xx000003DHscAAG"> <Id>001xx000003DHscAAG</Id> <Name>National Urban Technology Center</Name> </autoSuggestResults> <hasMoreResults>true</hasMoreResults> <meta> <nameFields> <entityApiName>Account</entityApiName> <fieldApiName>Name</fieldApiName> </nameFields> <nameFields> <entityApiName>ContentDocument</entityApiName> <fieldApiName>Title</fieldApiName> </nameFields> </meta> </suggestions> ``` <!-- document id=757b8f3fbf92216b3a61eef8e01267fc20060c1956e30773b7c5517febaa82c6 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-search-knowledge-articles.md --> # Search Knowledge Articles Searches for knowledge articles with specified search terms, language, data category group, and data category. This object is available in API version 56.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v56.0/actions/standard/searchKnowledgeArticles` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`searchText`|string|Search terms to be used in the knowledge article search.| |`languageCode`|string|The language code to be used in a knowledge article search. Valid values are language codes for fully supported languages.| |`dataCategoryGroupName`|string|The API name of the data category group to be used in the knowledge article search.| |`dataCategoryName`|string|The API name of the data category to be used in the knowledge article search.| |`resultsLimit`|integer|Optional. The maximum number of knowledge articles to return. Valid values are from 1 through 2000. By default, the maximum is 2000.| ## Outputs |Output|Type|Description| |------|----|-----------| |`knoweldgeArticlesList`|Apex|An Apex knowledge_bot__ArticlesList record that contains information about the knowledge articles that were returned.| <!-- document id=5769f40da9721b953fd5774b6d96fe8b146672719dba688cf5e2db26fa9a584f url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-layouts.md --> # Search Result Layouts Returns search result layout information for the objects in the query string. For each object, this call returns the list of fields displayed on the search results page as columns, the number of rows displayed on the first page, and the label used on the search results page. This call supports bulk fetch for up to 100 objects in a query. ## Syntax **URI:** `/services/data/vXX.X/search/layout/?q=commaDelimitedObjectList` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Response format** |Property|Type|Description| |--------|----|-----------| |`field`|String|Object and field name formatted with a period separating. For example: `Account.Name`.| |`format`|String|The type of date field, such as the date only or date and time. Only date related types are specified; otherwise, `null`.| |`label`|String|Name as it appears to users| |`name`|String|API name| ## Example See [Get Search Result Layouts for Objects.](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-retrieve-search-layouts.md) <!-- document id=c9bb38dba579d322d38adbd53a14890a9d53327b5e8bfdbe6e285d7d779cd01b url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-scope-order.md --> # Search Scope and Order Returns an ordered list of objects in the default global search scope of a logged-in user. Global search keeps track of which objects the user interacts with and how often, and arranges the search results accordingly. Objects used most frequently appear at the top of the list. The returned list reflects the object order in the user’s default search scope, including any pinned objects on the user’s search results page. This call is useful if you want to implement a custom search results page using the optimized global search scope. The search string must be URL-encoded. ## Syntax **URI:** `/services/data/vXX.X/search/scopeOrder` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` ## Example See [Get the Default Search Scope and Order](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-retrieve-search-scope-order.md). <!-- document id=7f8d6edf58517338b6ccf7bd343f89d1832717528b958debe7caf19003e37d5f url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-suggest-title-matches.md --> # Search Suggested Article Title Matches Returns a list of Salesforce Knowledge article titles that match the user’s search query string. Provides a shortcut to navigate directly to likely relevant articles before the user performs a search. This resource is available in REST API version 30.0 and later. Salesforce Knowledge must be enabled in your organization. The user must have the “View Articles” permission enabled. The articles suggested include only the articles the user can access, based on the data categories and article types the user has permissions to view. The Suggest Article Title Matches resource is designed to return display-ready data about likely relevant articles. Articles are suggested if their titles contain the entire query string, except stopwords, such as “a,” “for,” and “the.” For example, a search for `Backpacking for desert` returns the article, “Backpacking in the desert.” Articles with titles that include stopwords from the query string, such as “Backpacking for desert survival” in this example, appear before matching articles with titles that don’t include the stopwords. Stopwords at the end of the query string are treated as search terms. A wildcard is automatically appended to the last token in the query string. If the user’s search query contains quotation marks or wildcards, those symbols are automatically removed from the query string in the URI along with any other special characters. If the number of suggestions returned exceeds the limit specified in the request, the end of the response contains a field called `hasMoreResults`. Its value is `true` if the suggestions returned are only a subset of the suggestions available, and `false` otherwise. ## Syntax **URI:** `/services/data/vXX.X/search/suggestTitleMatches?q=searchString​&language=articleLanguage&publishStatus=articlePublicationStatus` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None required **Request parameters** |Parameter|Description| |---------|-----------| |`articleTypes`|Optional. Three-character ID prefixes indicating the desired article types. You can specify multiple values for this parameter in a single REST call, by repeating the parameter name for each value. For example, `articleTypes=ka0&articleTypes=ka1`.| |`categories`|Optional. The name of the data category group and name of the data category for desired articles, expressed as a JSON mapping. You can specify multiple data category group and data category pairs in this parameter. For example, `categories={"Regions":"Asia","Products":"Laptops"}`. Characters in the URL might need to be encoded. For this example, `categories=%7B%22Regions%22%3A%22Asia​%22%2C%22Products%22%3A%22Laptops%22%7D`.| |`channel`|Optional. The channel where the matching articles are visible. Valid values, default behavior, and specified-value requirements are the same as for the `channel` parameter in [Search Suggested Queries](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-search-suggest-queries.md).| |`language`|Required. The language of the user’s query. Specifies the language that matching articles are written in.| |`limit`|Optional. Specifies the maximum number of articles to return. If there are more suggested articles than the limit specified, the response body’s `hasMoreResults` property is `true`.| |`publishStatus`|Required. The article’s publication status. Valid values are `Draft` (articles aren’t published in Salesforce Knowledge), `Online` (articles are published in Salesforce Knowledge), or `Archived` (articles aren’t published and are available in Archived Articles view).| |`q`|Required. The user’s search query string, properly URL-encoded. Suggestions are returned only if the user’s query string meets the minimum length requirements: one character for queries in Chinese, Japanese, and Korean, and three characters for all other languages. Query strings exceeding the maximum length of 250 characters return an error.| |`topics`|Optional. The topic of the returned articles. For example:` topics=outlook&topics=email`.| |`validationStatus`|Optional. The validation status of returned articles.| ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/search/suggestTitleMatches? q=orange+banana&language=en_US&publishStatus=Online -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang { "autoSuggestResults" : [ { "attributes" : { "type" : "KnowledgeArticleVersion", "url" : "/services/data/v68.0/sobjects/KnowledgeArticleVersion/ka0D00000004CcQ" }, "Id" : "ka0D00000004CcQ", "UrlName" : "orange-banana", "Title" : "orange banana", "KnowledgeArticleId" : "kA0D00000004Cfz" } ], "hasMoreResults" : false } ``` <!-- document id=0784001d205b766d2254793ce013178c1ad413507b15fa8c1bd6982a4edcc809 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-suggest-queries.md --> # Search Suggested Queries Returns a list of suggested searches based on the user’s query string text matching searches that other users have performed in Salesforce Knowledge. Provides a way to improve search effectiveness, before the user performs a search. This resource is available in REST API version 30.0 and later. Salesforce Knowledge must be enabled in your organization. Queries are suggested if they exactly match the query string text. The text string must be a prefix within the query; it’s not considered a match if it appears within a word. For example, the text string `app` would return suggested queries *apple banana* and *banana apples* but not *pineapple*. If the number of suggestions returned exceeds the limit specified in the request, the end of the response contains a field called `hasMoreResults`. Its value is `true` if the suggestions returned are only a subset of the suggestions available, and `false` otherwise. If the user’s search query contains quotation marks or wildcards, those symbols are automatically removed from the query string in the URI. ## Syntax **URI:** `/services/data/vXX.X/search/suggestSearchQueries?q=searchString​&language=languageOfQuery` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None required **Request parameters** |Parameter|Description| |---------|-----------| |`channel`|Optional. Specifies the Salesforce Knowledge channel where the article can be viewed. Valid values are `AllChannels` (visible in all channels the user has access to), `App` (visible in the internal Salesforce Knowledge application), `Pkb` (visible in the public knowledge base), `Csp` (visible in the Customer Portal), or `Prm` (visible in the Partner Portal). See the channel default values and specified-value requirements after this table.| |`language`|Required. The language of the user’s query.| |`limit`|Optional. Specifies the maximum number of suggested searches to return. If there are more suggested queries than the limit specified, the response body’s `hasMoreResults` property is `true`.| |`q`|Required. The user’s search query string, properly URL-encoded. Suggestions are returned only if the user’s query string meets the minimum length requirements: one character for queries in Chinese, Japanese, and Korean, and three characters for all other languages. Query strings exceeding the maximum length of 250 characters return an error.| If `channel` isn’t specified, the default value is determined by the type of user. - `Pkb` for a guest user - `Csp` for a Customer Portal user - `Prm` for a Partner Portal user - `App` for any other type of user If `channel` is specified, the specified value may not be the actual value requested, because of certain requirements. - For guest, Customer Portal, and Partner Portal users, the specified value must match the default value for each user type. If the values don’t match or `AllChannels` is specified, then `App` replaces the specified value. - For all users other than guest, Customer Portal, and Partner Portal users, if `Pkb`, `Csp`, `Prm`, or `App` are specified, then the specified value is used. If `AllChannels` is specified, then `App` replaces the specified value. Valid `channel` values (also referenced by Search Suggested Article Title Matches): - `AllChannels`–Visible in all channels the user has access to - `App`–Visible in the internal Salesforce Knowledge application - `Pkb`–Visible in the public knowledge base - `Csp`–Visible in the Customer Portal - `Prm`–Visible in the Partner Portal ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/search/suggestSearchQueries? q=app&language=en_US -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang { "autoSuggestResults" : [ { "0" : "apple", "1" : "apple banana", } ], "hasMoreResults" : false } ``` <!-- document id=2f05bd626081187bd1d22e0040d402db36fc84f61df483653659ca6650e240c1 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-parameterized-post.md --> # Search with Parameters in the Request Body Search by defining parameters in the request body Access advanced search that offers more control over how the search query executes. It also allows you to filter using several DataCategories, networks (sites), orderBy constraints, and filters. This resource is available in REST API version 36.0 and later. ## Syntax **URI:** `/services/data/vXX.X/parameterizedSearch/` **Formats:** JSON, XML **HTTP methods:** POST **Authentication:** `Authorization: Bearer token` **Required Global Parameters** | Name | Description | | ---- | ----------------------------------------------------------------------------------------------------------------- | | `q` | A search string that is properly URL-encoded. SOSL clauses aren’t supported. Available in version 36.0 and later. | **Optional Global Parameters** | Name | Type | Description | | ----------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataCategories` | [dataCategoriesFilter[]](#syntax) | If an organization uses Salesforce Knowledge articles or answers, filter all search results based on one or more data categories. When using `dataCategories`, specify a Salesforce Knowledge article or answer type with [sobjects](#syntax) and the required parameters. | | `defaultLimit` | string | Single value. The maximum number of results to return for each `sobject` (GET) or `sobjects` (POST) specified. The maximum `defaultLimit` is 2000. At least one `sobject` must be specified. GET example: `defaultLimit=10&sobject=Account&sobject=Contact`. When an `sobject` limit is specified using `sobject.limit=value`, such as `Account.limit=10`, this parameter is ignored for that object. | | `division` | string | Single value. Filters search results based on the division field. For example in the GET method, `division=global`. Specify a division by its name rather than ID. All searches within a specific division also include the `global` division. | | `fields` | string[] | Array of one or more fields to return in the response for each `[sobjects](#syntax)` specified. At least one `sobjects` must be specified at the global level. The global `fields` parameter is overridden when `[sobjects](#syntax)` fields are specified. Such as, in the previous example, `Id`, `FirstName`, and `LastName` is returned for `Contact` instead of the global fields of `Id`, `Name` and `Phone`. If unspecified, then the search results contain the IDs of records matching all fields for the specified object. The following optional functions can be used within the `fields` parameter: `toLabel` (translates response field value into the user’s language; requires extra setup), `convertCurrency` (converts response currency fields to the user’s currency; requires extra setup; multi-currency must be enabled in the org), and `format` (applies localized formatting to standard and custom number, date, time, and currency fields). Aliasing is supported within `fields` for `toLabel`, `convertCurrency`, and `format`. In addition, aliasing is required when the query includes the same field multiple times. | | `in` | string | Scope of fields to search. If you specify one or more scope values, the fields are returned for all found objects. Use one of the following values: `ALL`, `NAME`, `EMAIL`, `PHONE`, or `SIDEBAR`. This clause doesn't apply to articles, documents, feed comments, feed items, files, products, and solutions. If any of these objects are specified, the search isn’t limited to specific fields; all fields are searched. | | `metadata` | string | Specifies if metadata should be returned in the response. No metadata is returned by default. To include metadata in the response, use the `LABELS` value, which returns the display label for the fields returned in search results. For example: `?q=Acme&metadata=LABELS` | | `netWorkIds` | string[] | Filters search results by an array. A network ID represents the Experience Cloud site ID. | | `offset` | string | Single value. The starting row offset into the result set returned. The maximum `offset` is 2000. Only one `sobject` can be specified when using this parameter. | | `overallLimit` | string | Single value. The maximum number of results to return across all `sobject` parameters specified. The maximum `overallLimit` is 2000. | | `pricebookId` | string | Single value. Filters product search results by a price book ID for only the Product2 object. The price book ID must be associated with the product that you’re searching for. For example, `?q=laptop&sobject=product2&pricebookId=01sxx0000002MffAAE` | | `snippet` | string | The target length (maximum number of snippet characters) to return in Salesforce Knowledge article, case, case comment, feed, feed comment, idea, and idea comment search results. The `snippet` parameter displays contextual excerpts and highlights the search term for each article in the search results. Snippet results are used to differentiate matches to the search term in article search results. The target length can be from 50 to 1000 characters. Snippet and highlights are generated from email, text, and text area (long and rich) fields. Snippets aren’t displayed for partially matching searches or if the user doesn’t have access to the field that contains the snippet. Snippets are only displayed when 20 or fewer results are returned on a page. At least one of the following `sobject` values must be specified: to search a specific article type, use the article type name with the suffix `__kav`; to search all article types, use `KnowledgeArticleVersion`; to search case, case comment, feed, feed comment, idea, and idea comment types, use `Case`, `CaseComment`, `FeedItem`, `FeedComment`, `Idea`, and `IdeaComment`. For example, `q=tourism&sobject=Case&snippet=500`. | | `sobjects` | [sobjectsFilter[]](#syntax) | Objects to return in the response. Must contain valid object types. Use with the required parameters. If unspecified, then the search results contain the IDs of all objects. | | `spellCorrection` | boolean | Specifies whether spell correction is enabled for a user’s search. When set to `true`, spell correction is enabled for searches that support spell correction. The default value is `true`. For example: `q=Acme&sobject=Account&Account.fields=id&spellCorrection=true` | | `updateTracking` | string | Specifies a value of `true` to track keywords that are used in Salesforce Knowledge article searches only. If unspecified, the default value of `false` is applied. | | `updateViewStat` | string | Specifies a value of `true` to update an article’s view statistics. Valid only for Salesforce Knowledge article searches. If unspecified, the default value of `false` is applied. | Example `dataCategories`: ```nolang { "q":"Acme", "fields":["id", "title"], "sobjects":[{"name":"KnowledgeArticleVersion", "where":"language='en_US' and publishstatus='draft'"}], "dataCategories":[ {"groupName" : "location__c", "operator":"below", "categories":["North_America__c"]} ] } ``` Example `fields`: ```nolang { "q":"Acme", "fields":["Id", "Name", "Phone"], "sobjects":[{"name": "Account"}, {"name": "Contact", "fields":["Id", "FirstName", "LastName"]}, {"name": "Lead"}] } ``` Example `toLabel`: ```nolang { ... "sobjects":[ {"name": "Lead", "fields":["Id", "toLabel(Status)"]}, ... } ``` Example `convertCurrency`: ```nolang { ... "sobjects":[ {"name": "Opportunity", "fields":["Id", "convertCurrency(Amount)"]}] ... } ``` Example `format`: ```nolang { ... "sobjects":[ {"name": "Opportunity", "fields":["Id", "format(Amount)"]}] ... } ``` Example aliasing in `fields`: ```nolang { ... "sobjects":[ {"name": "Opportunity", "fields":["Id", "format(Amount) AliasAmount"]}] ... } ``` Example `sobjects`: ```nolang { "q":"Acme", "fields":["id", "title"], "sobjects":[{"name":"Solution__kav", "where":"language='en_US' and publishstatus='draft'"}, {"name":"FAQ__kav", "where":"language='en_US' and publishstatus='draft'"}] } ``` **`dataCategoriesFilter[]` Parameters** Parameters must be specified in the order presented in the table (`groupName`, `operator`, `categories`). | Name | Type | Description | | ------------ | -------- | ---------------------------------------------------------- | | `groupName` | string | The name of the data category group to filter by. | | `operator` | string | Valid values: `ABOVE`, `ABOVE_OR_BELOW`, `AT`, or `BELOW`. | | `categories` | string[] | The name of the categories to filter by. | **`sobjectsFilter[]` Parameters** | Name | Type | Description | | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fields` | string[] | Array of one or more fields to return in the response for the `sobject`. | | `limit` | string | Specify the maximum number of rows that are returned for the `sobject`. | | `name` | string | Name of the `sobject` to return in the response. | | `orderBy` | string | Controls the field order of the results using the following syntax `"orderBy" : "field {ASC\|DESC} [NULLS_{FIRST\|LAST}]"`. Valid values: `ASC` (ascending; default), `DESC` (descending), `NULLS_FIRST` (null records at the beginning of the results; default), or `NULLS_LAST` (null records at the end of the results). | | `where` | string | Filter search results for this object by specific field values. For example, `where : conditionExpression`. Here the `conditionExpression` of the WHERE clause uses the following syntax: `fieldExpression [logicalOperator fieldExpression2 ... ]`. Add multiple field expressions to a condition expression by using logical and comparison operators. | Example `orderBy`: ```nolang { ... "sobjects":[ {"name": "Account", "fields":["Id", "name"], "orderBy": "Name DESC Nulls_last"}] ... } ``` ## Example **Example Request Body** ```nolang { "q":"Smith", "fields" : ["id", "firstName", "lastName"], "sobjects":[{"fields":["id", "NumberOfEmployees"], "name": "Account", "limit":20}, {"name": "Contact"}], "in":"ALL", "overallLimit":100, "defaultLimit":10 } ``` <!-- document id=eb0901ccba37a651c3548facfd56ed733f898c6d4a624547d32425f56740c945 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-search-parameterized-get.md --> # Search with Parameters in the URI Get search results using simple URI parameters instead of using SOSL. Make basic queries without defining a large SOSL query. Use this API when you have a basic use case to cover, replacing FIND searchString IN ALL FIELDS by just including the search string in the URI. This resource is available in REST API version 36.0 and later. ## Syntax **URI** `/services/data/vXX.X/parameterizedSearch/?q=searchString` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Required Global Parameters** | Name | Description | | ---- | ---------------------------------------------------------------------------------- | | `q` | A search string that is properly URL-encoded. Available in version 36.0 and later. | **Note:** SOSL clauses aren’t supported. **Optional Global Parameters** | Name | Type | Description | | ----------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dataCategory` | string | Single value. If an organization uses Salesforce Knowledge articles or answers, `dataCategory` filters all search results based on one data category. For example, `dataCategory=GlobalCategory__c below NorthAmerica__c`. When using `dataCategories`, specify a Salesforce Knowledge article or answer type with `sobject` and all the required parameters. If you require multiple `dataCategory` filters, use `dataCategories` with the POST method. | | `defaultLimit` | string | Single value. The maximum number of results to return for each `sobject` (GET) or `sobjects` (POST) specified. The maximum `defaultLimit` is 2000. At least one `sobject` must be specified. GET example: `defaultLimit=10&sobject=Account&sobject=Contact`. When an `sobject` limit is specified using `sobject.limit=value`, such as `Account.limit=10`, this parameter is ignored for that object. | | `division` | string | Single value. Filters search results based on the division field. For example in the GET method, `division=global`. Specify a division by its name rather than ID. All searches within a specific division also include the `global` division. | | `fields` | string | Comma-separated list of one or more fields to return in the response for each `[sobject](#syntax)` specified. At least one `sobject` must be specified at the global level. For example: `fields=id&sobject=Account&sobject=Contact`. The global `fields` parameter is overridden when `[sobject](#syntax)` are specified using `sobject.fields=field names`. For example, `Contact.fields=id,FirstName,LastName` would override the global setting of just returning the `id`. If unspecified, then the search results contain the IDs of records matching all fields for the specified object. The following optional functions can be used within the `fields` parameter: `toLabel` (translates response field value into the user’s language; for example, `Lead.fields=id,toLabel(Status)`; requires extra setup), `convertCurrency` (converts response currency fields to the user’s currency; for example, `Opportunity.fields=id,convertCurrency(Amount)`; requires extra setup and multi-currency must be enabled in your org), and `format` (applies localized formatting to standard and custom number, date, time, and currency fields; for example, `Opportunity.fields=id,format(Amount)`). Aliasing is supported in `fields` for `toLabel`, `convertCurrency`, and `format`. In addition, aliasing is required when the query includes the same field multiple times. For example, `Opportunity.fields=id,format(Amount) AliasAmount`. | | `in` | string | Scope of fields to search. If you specify one or more scope values, the fields are returned for all found objects. Use one of the following values: `ALL`, `NAME`, `EMAIL`, `PHONE`, or `SIDEBAR`. This clause doesn't apply to articles, documents, feed comments, feed items, files, products, and solutions. If any of these objects are specified, the search isn’t limited to specific fields; all fields are searched. | | `metadata` | string | Specifies if metadata should be returned in the response. No metadata is returned by default. To include metadata in the response, use the `LABELS` value, which returns the display label for the fields returned in search results. For example: `?q=Acme&metadata=LABELS` | | `netWorkIds` | string | Filters search results by a comma-separated list. A network ID represents the Experience Cloud site ID. | | `offset` | string | Single value. The starting row offset into the result set returned. The maximum `offset` is 2000. Only one `sobject` can be specified when using this parameter. | | `overallLimit` | string | Single value. The maximum number of results to return across all `sobject` parameters specified. The maximum `overallLimit` is 2000. | | `pricebookId` | string | Single value. Filters product search results by a price book ID for only the Product2 object. The price book ID must be associated with the product that you’re searching for. For example, `?q=laptop&sobject=product2&pricebookId=01sxx0000002MffAAE` | | `snippet` | string | The target length (maximum number of snippet characters) to return in Salesforce Knowledge article, case, case comment, feed, feed comment, idea, and idea comment search results. The `snippet` parameter displays contextual excerpts and highlights the search term for each article in the search results. Snippet results are used to differentiate matches to the search term in article search results. The target length can be from 50 to 1000 characters. Snippet and highlights are generated from email, text, and text area (long and rich) fields. Snippets aren’t displayed for partially matching searches or if the user doesn’t have access to the field that contains the snippet. Snippets are only displayed when 20 or fewer results are returned on a page. At least one of the following `sobject` values must be specified: to search a specific article type, use the article type name with the suffix `__kav`; to search all article types, use `KnowledgeArticleVersion`; to search case, case comment, feed, feed comment, idea, and idea comment types, use `Case`, `CaseComment`, `FeedItem`, `FeedComment`, `Idea`, and `IdeaComment`. For example, `q=tourism&sobject=Case&snippet=500`. | | `sobject` | string | Objects to return in the response. Must be a valid object type. You can use multiple `sobject` values, such as `sobject=Account&sobject=Contact`. If unspecified, then the search results contain the IDs of all objects. | | `spellCorrection` | boolean | Specifies whether spell correction is enabled for a user’s search. When set to `true`, spell correction is enabled for searches that support spell correction. The default value is `true`. For example: `q=Acme&sobject=Account&Account.fields=id&spellCorrection=true` | | `updateTracking` | string | Specifies a value of `true` to track keywords that are used in Salesforce Knowledge article searches only. If unspecified, the default value of `false` is applied. | | `updateViewStat` | string | Specifies a value of `true` to update an article’s view statistics. Valid only for Salesforce Knowledge article searches. If unspecified, the default value of `false` is applied. | Example `dataCategory`: ```nolang q=tourism&sobject=KnowledgeArticleVersion&KnowledgeArticleVersion.where= language='en_US'+and+publishStatus='online'&KnowledgeArticleVersion.fields= id,title&dataCategory=Location__c+Below+North_America__c ``` **`sobject`-level Parameters** The following optional parameters can be used with the `sobject` parameter in a GET method to further refine search results. These settings would override any settings specified at the global level. The format is _sobject_._parameter_, such as `Account.fields`. An `sobject` must be specified to use these parameters, for example, `sobject=Account&Account.fields=id,name`. | Name | Type | Description | | --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fields` | string | Comma-separated list of one or more fields to return in the response. For example, `KnowledgeArticleVersion.fields=id,title`. | | `limit` | string | Specifies the maximum number of rows that are returned for the `sobject`. For example, `Account.limit=10`. | | `orderBy` | string | Controls the field order of the results using the following syntax `orderBy = field {ASC\|DESC} [NULLS_{FIRST\|LAST}]`. For example: `Account.orderBy=Name`. Valid values: `ASC` (ascending; default), `DESC` (descending), `NULLS_FIRST` (null records at the beginning of the results; default), or `NULLS_LAST` (null records at the end of the results). | | `where` | string | Filter search results for this object by specific field values. For example, `Account.where = conditionExpression`. Here the `conditionExpression` of the WHERE clause uses the following syntax: `fieldExpression [logicalOperator fieldExpression2 ... ]`. Add multiple field expressions to a condition expression by using logical and comparison operators. For example, `KnowledgeArticleVersion.where=publishstatus='online' and language='en_US'`. | ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/parameterizedSearch/?q=Acme&sobject=Account&Account.fields=id,name&Account.limit=10 ``` <!-- document id=193c04922cc35ed76b1a0ce63ee57caf103c0d5bc4fe30c1d83ec154f571473f url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-search.md --> # search() Executes a text search in your organization's data. ## Syntax ```java SearchResult = connection.search(String searchString); ``` ## Usage Use [`search()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-search.md) to search for records based on a search string. The search call supports searching custom objects. For an extensive discussion about the syntax and rules used for text searches, see the [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/). Certain objects cannot be searched via the API, such as [Attachment](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_attachment.htm) objects. To search an object via the search() call, the object must be configured as searchable (`isSearchable` is `true`). To determine whether an object can be searched, your client application can invoke the [`describeSObjects()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-describesobjects.md) call on the object and inspect its `searchable` property. ## Sample Code—Java This sample makes the `search()` call by passing it a SOSL query, which returns contacts, leads, and accounts whose phone fields contain a specified value. Next, it gets the sObject records from the results and stores the records in arrays depending on the record type. Finally, it writes the fields of the returned contacts, leads, and accounts to the console. <!-- otherprops: java set_clipboard --> ```codesegment public void searchSample() { try { // Perform the search using the SOSL query. SearchResult sr = connection.search( "FIND {4159017000} IN Phone FIELDS RETURNING " + "Contact(Id, Phone, FirstName, LastName), " + "Lead(Id, Phone, FirstName, LastName), " + "Account(Id, Phone, Name)"); // Get the records from the search results. SearchRecord[] records = sr.getSearchRecords(); ArrayList<Contact> contacts = new ArrayList<Contact>(); ArrayList<Lead> leads = new ArrayList<Lead>(); ArrayList<Account> accounts = new ArrayList<Account>(); // For each record returned, find out if it's a // contact, lead, or account and add it to the // appropriate array, then write the records // to the console. if (records.length > 0) { for (int i = 0; i < records.length; i++) { SObject record = records[i].getRecord(); if (record instanceof Contact) { contacts.add((Contact) record); } else if (record instanceof Lead) { leads.add((Lead) record); } else if (record instanceof Account) { accounts.add((Account) record); } } System.out.println("Found " + contacts.size() + " contacts."); for (Contact c : contacts) { System.out.println(c.getId() + ", " + c.getFirstName() + ", " + c.getLastName() + ", " + c.getPhone()); } System.out.println("Found " + leads.size() + " leads."); for (Lead d : leads) { System.out.println(d.getId() + ", " + d.getFirstName() + ", " + d.getLastName() + ", " + d.getPhone()); } System.out.println("Found " + accounts.size() + " accounts."); for (Account a : accounts) { System.out.println(a.getId() + ", " + a.getName() + ", " + a.getPhone()); } } else { System.out.println("No records were found for the search."); } } catch (Exception ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample makes the `search()` call by passing it a SOSL query, which returns contacts, leads, and accounts whose phone fields contain a specified value. Next, it gets the sObject records from the results and stores the records in arrays depending on the record type. Finally, it writes the fields of the returned contacts, leads, and accounts to the console. <!-- otherprops: c_sharp set_clipboard --> ```classsearch_csharp_enterprise public void searchSample() { try { // Perform the search using the SOSL query. SearchResult sr = binding.search( "FIND {4159017000} IN Phone FIELDS RETURNING " + "Contact(Id, Phone, FirstName, LastName), " + "Lead(Id, Phone, FirstName, LastName), " + "Account(Id, Phone, Name)"); // Get the records from the search results. SearchRecord[] records = sr.searchRecords; List<Contact> contacts = new List<Contact>(); List<Lead> leads = new List<Lead>(); List<Account> accounts = new List<Account>(); // For each record returned, find out if it's a // contact, lead, or account and add it to the // appropriate array, then write the records // to the console. if (records.Length > 0) { for (int i = 0; i < records.Length; i++) { sObject record = records[i].record; if (record is Contact) { contacts.Add((Contact)record); } else if (record is Lead) { leads.Add((Lead)record); } else if (record is Account) { accounts.Add((Account)record); } } Console.WriteLine("Found " + contacts.Count + " contacts."); foreach (Contact c in contacts) { Console.WriteLine(c.Id + ", " + c.FirstName + ", " + c.LastName + ", " + c.Phone); } Console.WriteLine("Found " + leads.Count + " leads."); foreach (Lead d in leads) { Console.WriteLine(d.Id + ", " + d.FirstName + ", " + d.LastName + ", " + d.Phone); } Console.WriteLine("Found " + accounts.Count + " accounts."); foreach (Account a in accounts) { Console.WriteLine(a.Id + ", " + a.Name + ", " + a.Phone); } } else { Console.WriteLine("No records were found for the search."); } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`search`|string|Search string that specifies the text expression to search for, the scope of fields to search, the list of objects and fields to retrieve, and the maximum number of records to return. For more information, see the [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/).| ## Response [SearchResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-search-searchresult.md) ## Fault [`InvalidFieldFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`InvalidSObjectFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`MalformedSearchFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [API Call Basics](https://developer.salesforce.com/docs/platform/api/guide/calls.md) <!-- document id=9ed5c116644d995769dacfe8a2ec5418aa6d3f92876ee926340fc6c5989b11b0 url=/developer/current/en-us/platform/platform-events/guides/platform-events/objects/sforce-api-objects-searchindexjobstatusevent.md --> # SearchIndexJobStatusEvent Notifies subscribers of changes to the status of the Data Cloud search index job, such as index refresh status and index run-time status. This object is available in API version 60.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/SearchIndexJobStatusEvent` ## Event Delivery Allocation Enforced Yes ## Special Access Rules SearchIndexJobStatusEvent is available only if Data Cloud is enabled. ## Fields ### `ApiName` **Type:** string **Properties:** Nillable **Description:** The search index API name. ### `ErrorCode` **Type:** string **Properties:** Nillable **Description:** Reference code for the type of error that occurred. ### `EventCreationDate` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the event occurred. ### `EventPublishDate` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the event was published. ### `EventType` **Type:** string **Properties:** Nillable **Description:** The type of event that occurred. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `IndexRefreshedOn` **Type:** dateTime **Properties:** Nillable **Description:** The date and time of the last refresh on the index. ### `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. ### `RuntimeStatus` **Type:** string **Properties:** Nillable **Description:** The last run status of the search index such as `Ready`, `In Progress`, or `Failed`. ### `SchemaVersion` **Type:** string **Properties:** Nillable **Description:** The version of the event schema. <!-- document id=fe6c324e8ab6b65b7b5ee8a5495c82065f81985e83682633c301e984911344a0 url=/developer/current/en-us/platform/salesforce-large-data-volumes-bp/guides/cce/ldv-deployments/ldv-deployments-best-practices-searching.md --> # Searching |Goal|Best Practice| |----|-------------| |Reducing the number of records to return|Keep searches specific and avoid using wildcards, if possible. For example, search with `Michael` instead of `Mi*`.| |Reducing the number of joins|Use single-object searches for greater speed and accuracy.| |Improving efficiency|Use the setup area for searching to enable language optimizations, and turn on enhanced lookups and auto-complete for better performance on lookup fields.| |Improving search performance|In some cases, partition data with divisions. (See [Divisions](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-infrastructure-divisions.md).)| |Reducing the time it takes to index inserts and updates for large data volumes|See [Search Architecture](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-concepts-search-architecture.md).| <!-- document id=0b5de4bc77efa92d6394747df2b93b94ad9c65d672ed344e52b37ded65e76daa url=/developer/current/en-us/platform/api/guides/api/calls/sforce-api-calls-search-searchresult.md --> # SearchResult The `search()` call returns a SearchResult object. A SearchResult object has these fields. |Name|Type|Description| |----|----|-----------| |`queryId`|string|Unique identifier for the `SOSL` search.| |`searchRecords`|[SearchRecord](#searchrecord)[]|Array of SearchRecord objects, each of which contains an [sObject.](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject)| |`searchResultsMetadata`|[SearchResultsMetadata](#searchresultsmetadata)|Metadata for SearchRecords.| ## SearchRecord Represents an individual record returned from a search. |Name|Type|Description| |----|----|-----------| |`record`|[sObject](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-concepts-core-data-objects.md#sobject)|The individual record returned by the search.| |`searchRecordMetadata`|[SearchRecordMetadata](#searchrecordmetadata)|Metadata for `searchRecords`.| |`snippet`|[SearchSnippet](#searchsnippet)|On the search results page, shows terms that match the search string, highlighted within the surrounding text.| ## SearchRecordMetadata Metadata for search results at the record level. |Name|Type|Description| |----|----|-----------| |`searchPromoted`|boolean|Indicates that an article has been promoted in search results. Admins define promoted search terms by adding promoted terms to knowledge articles. Users who search for these keywords see the article first in search results. Available in API version 42.0 and later.| |`spellCorrected`|boolean|Indicates that a record matches a spell-corrected search term. Appears in the response only when true.| ## SearchSnippet Excerpts shown on search results pages for article, case, feed, and idea searches. |Name|Type|Description| |----|----|-----------| |`text`|string|The excerpt that contains the match for the search term.| |`wholeFields`|[WholeFields](#wholefields)|The list of highlighted fields.| ## WholeFields Contains the complete text of each field that contains highlighting for terms that match the search query. The highlighted terms are surrounded by `<mark>` tags. |Name|Type|Description| |----|----|-----------| |`name`|string|The name of the highlighted field.| |`value`|string|The highlighted text.| ## SearchResultsMetadata Global metadata for the search result. |Name|Type|Description| |----|----|-----------| |`entityMetadata`|[EntitySearchMetadata](#entitysearchmetadata)|Search results metadata at the object level.| ## EntitySearchMetadata Metadata for search results at the object level. |Name|Type|Description| |----|----|-----------| |`fieldMetadata`|[FieldLevelSearchMetadata](#fieldlevelsearchmetadata)|Metadata for search results at the field level.| |`searchPromotedMetadata`|[EntitySearchPromotionMetadata](#entitysearchpromotionmetadata)|Metadata for search term promotion at the object level. Available in API version 42.0 and later.| |`spellCorrectionMetadata`|[EntitySpellCorrectionMetadata](#entityspellcorrectionmetadata)|Metadata for spelling correction at the object level.| |`entityName`|string|Identifies the object.| ## FieldLevelSearchMetadata Metadata for search results at the field level. |Name|Type|Description| |----|----|-----------| |`name`|string|The field name.| |`label`|string|The field label.| |`type`|string|The field type.| ## EntitySearchPromotionMetadata Metadata for search term promotion at the object level. Appears in the response only when at least one article for an object is a promoted result. Available in API version 42.0 and later. |Name|Type|Description| |----|----|-----------| |`promotedResultCount`|int|Count of promoted article results at the object level.| ## EntitySpellCorrectionMetadata Metadata for spelling correction at the object level. Appears in the response only when at least one record for an object matches a spell-corrected search term. |Name|Type|Description| |----|----|-----------| |`correctedQuery`|string|The spell-corrected search term.| |`hasNonCorrectedResults`|boolean|If `true`, indicates that the user has access to at least one record that matches a search term that wasn't spell-corrected. Each object sometimes returns a different value.| **See Also** - [WITH SNIPPET](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_sosl_with_snippet.htm) - [WITH SPELL_CORRECTION](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_sosl_with_spell_correction.htm) <!-- document id=3ac1619b1cc7ab605168afde07e9cfe1a387a600cf82f849352f8576a002e2f3 url=/developer/current/en-us/platform/api/guides/api/concepts/sforce-api-concepts-security.md --> # Security and the API Client apps that access your Salesforce data are subject to the same security protections that are used in the Salesforce user interface. Additional protection is available for orgs that install AppExchange managed packages if those packages contain components that access Salesforce via the API. ## User Authentication Client apps must log in using valid credentials. After validating, the server provides the client app with a: - [`sessionId`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) that is set into the session header so that all subsequent calls to the Web service are authenticated - URL address ([`serverUrl`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md)) for the client app's web service requests Salesforce supports only the Transport Layer Security (TLS) protocol and frontdoor.jsp. Ciphers must have a key length of at least 128 bits. ## User Profile and Permission Sets Configuration As an org’s Salesforce admin, you control which features and views are available to users by configuring profiles and permission sets and assigning users to them. To access the API to issue calls and receive the call results, a user must have the API Enabled permission. Client apps can query or update only those objects and fields to which they have access via the permissions of the logged-in user. To create, edit, or delete a profile, from Setup, enter `Profiles` in the Quick Find box, then select **Profiles**. To create, edit, or delete a permission set, from Setup, enter `Permission Sets` in the Quick Find box, then select **Permission Sets**. **note:** The web services WSDL files return all available objects and fields for an org. ## Security Token When users log in to Salesforce via the user interface, the API, or a desktop client such as Salesforce for Outlook, Connect Offline, Connect for Office, or the Data Loader, Salesforce authorizes the login as follows. 1. Salesforce checks whether the user’s profile has login-hour restrictions. If the user’s profile specifies login-hour restrictions, login attempts outside the specified hours are denied. 2. If the user has the Multi-Factor Authentication for User Interface Logins permission, the Salesforce login process prompts the user for an identity verification method in addition to their username and password. If the user’s account isn’t already connected to a verification method, such as the Salesforce Authenticator mobile app, Salesforce prompts the user to register a method. 3. If the user has the Multi-Factor Authentication for API Logins permission and connected an authenticator app to the account, the user must enter a verification code (TOTP) generated by the authenticator app. If the user uses the standard security token, Salesforce returns an error. 4. Salesforce then checks whether the user’s profile defines IP address range restrictions. If so, logins from outside the IP address range are denied. If the **Enforce login IP ranges on every request** session setting is enabled, the IP address restrictions are enforced for each page request, including requests from client apps. 5. If profile-based IP address restrictions aren’t set, Salesforce checks whether the user is logging in from a device that was previously used to access Salesforce. - If the user is logging in from a device and browser that Salesforce recognizes, the login is allowed. - If the user is logging in from an IP address on your org’s trusted IP address list, the login is allowed. - If the user isn’t logging in from a trusted IP address, device, or browser that Salesforce recognizes, the login is blocked. Whenever a login is blocked or returns an API login fault, Salesforce verifies the user’s identity. - For access via the user interface, the user is prompted to verify using Salesforce Authenticator (version 2 or later) or enter a verification code. **note:** Users aren’t asked for a verification code the first time they log in to Salesforce. - For access via the API or client app, if the Multi-Factor Authentication on API Logins permission is set on the user profile, users enter a TOTP verification code generated by an authenticator app. If the permission isn’t set, users must add their security token to the end of their password to log in. A security token is a generated key from Salesforce. For example, if a user’s password is `mypassword` and the security token is `XXXXXXXXXX`, the user enters `mypasswordXXXXXXXXXX` to log in. Some client apps have a separate field for the security token. Users can get their security token by changing their password or resetting their security token via the Salesforce user interface. When a user changes a password or resets a security token, Salesforce sends a new security token to the email address on the user’s Salesforce record. The security token is valid until the user resets the security token, changes a password, or has a password reset. **note:** Before you access Salesforce from a new IP address, we recommend that you get your security token from a trusted network using Reset My Security Token. For more information about tokens, see [Reset Your Security Token](https://help.salesforce.com/articleView?id=xcloud.user_security_token.htm&type=5) in Salesforce Help. When a user’s password is changed, the user’s security token is automatically reset. To log in after the reset, the user adds the generated security token to the end of the password. Or the user enters the new password after you add the user’s IP address to the org’s list of trusted IP addresses. If you reset the password of a user with the API only user permission, the user doesn’t receive a security token reset email. If you want API only users to receive a security token reset email when you reset their password, take these steps. 1. Temporarily assign the user to a profile that doesn’t have the API only user permission. For more information on user profiles and permissions, see [User Permissions and Access](https://help.salesforce.com/articleView?id=platform.permissions_about_users_access.htm&type=5). 2. Ask the user to [manually reset their security token](https://help.salesforce.com/articleView?id=xcloud.user_security_token.htm&type=5). 3. Reassign the user to a profile with the API only user permission. If single sign-on (SSO) is enabled, users who access the API or a desktop client can’t log in unless their IP address is included on your org’s list of trusted IP addresses or on their profile, if their profile has IP address restrictions set. The delegated authentication authority usually handles login lockout policies for users with the Uses Single Sign-On permission. However, if the security token is enabled, your login lockout settings determine how many times a user can try to log in with an invalid security token before getting locked out. For more information, see Setting Login Restrictions and Setting Password Policies in Salesforce Help. ## Sharing Sharing refers to the act of granting read or write access to a user or group so that they can view or edit a record owned by other users, if the default access levels don’t permit such access. All API calls respect the sharing model. The following table describes the types of access levels. |API Value|Salesforce User Interface Label|API Picklist Label|Description| |---------|-------------------------------|------------------|-----------| |`None`|`Private`|`Private`|Only the record owner and [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) above that role in the hierarchy can view and edit the record.| |`Read`|`Read Only`|`Read Only`|All [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) and [Groups](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_group.htm) can view the record but not edit it. Only the owner and users above that role in the hierarchy can edit the record.| |`Edit`|`Read/Write`|`Read/Write`|All [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) and [Groups](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_group.htm) can view and edit the record.| |`ReadEditTransfer`|`Read/Write/Transfer`|`Read/Write/Transfer`|All [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) and [Groups](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_group.htm) can view, edit, delete, and transfer the record. (Only available for cases and leads as an org-wide default setting.)| |`All`|`Full Access`|`Owner`|All [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) and [Groups](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_group.htm) can view, edit, transfer, delete, and share the record. (Only available for campaigns as an org-wide default setting.)| |`ControlledByParent`|`Controlled by Parent`|`Controlled By Parent`|(Contacts only.) All [Users](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) and [Groups](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_group.htm) can perform an action (such as view, edit, or delete) on the contact based on whether he or she can perform that same action on the record associated with it.| Not all access levels are available for every object. See the Fields table for each object to learn which access levels are available, as well as other sharing details specific to that object. For more information about sharing in general, see Salesforce Help. **note:** In the API, you can create and update objects such as [AccountShare](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_accountshare.htm) and [OpportunityShare](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_opportunityshare.htm) that define sharing entries for records. ## Implicit Restrictions for Objects and Fields Certain objects can be created or deleted only in the Salesforce user interface. Other objects are read-only—client apps cannot create(), delete(), or update() such objects. Similarly, certain fields within some objects can be specified on create() but not on update(). Other fields are read-only—client apps cannot specify field values in create() or update() calls. For more information, see the respective object descriptions in [Object Basics](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_concepts.htm). ## API Access in Salesforce AppExchange Packages The API allows access to objects and calls based on the permissions of the user who logs into the API. To prevent security issues from arising when installed packages have components that access data via the API, Salesforce provides additional security: - When a developer creates an AppExchange package with components that access the API, the developer can restrict the API access for those components. - When an administrator installs an AppExchange package, the administrator can accept or reject the access. Rejecting the access cancels the installation. - After an administrator installs a package, the administrator can restrict the API access of components in the package that access the API. Editing API access for a package is done in the Salesforce user interface. For more information, see *Manage API and Dynamic Apex Access in Packages* in Salesforce Help. API access for a package affects the API requests originating from components within the package; it determines the objects that the API requests can access. If the API access for a package is not defined, then the objects that the API requests have access to are determined by the user's permissions. The API access for a package never allows users to do more than the permissions granted to the user. API access in a package only reduces what the user's permissions allow. Choosing `Restricted` for the `API Access` setting in a package affects the following: - API access in a package overrides the following user permissions: - Author Apex - Customize Application - Edit HTML Templates - Edit Read Only Fields - Manage Billing - Manage Call Centers - Manage Categories - Manage Custom Report Types - Manage Dashboards - Manage Letterheads - Manage Package Licenses - Manage Public Documents - Manage Public List Views - Manage Public Reports - Manage Public Templates - Manage Users - Transfer Record - Use Team Reassignment Wizards - View Setup and Configuration - Weekly Export Data - If `Read`, `Create`, `Edit`, and `Delete` access aren’t selected in the API access setting for objects, users don’t have access to those objects from the package components, even if the user has the Modify All Data and View All Data permissions. - A package with `Restricted` API access can’t create users. - Salesforce denies access to Web service and `executeanonymous` requests from an AppExchange package that has `Restricted` access. The following considerations also apply to API access in packages: To manage API access to packages, see “Manage API and Dynamic Apex Access in Packages” in Salesforce Help. ## Outbound Port Restrictions For security reasons, Salesforce restricts the outbound ports you can specify to one of the following: - 80: This port only accepts HTTP connections. - 443: This port only accepts HTTPS connections. - 1024–65535 (inclusive): These ports accept HTTP or HTTPS connections. The port restriction applies to any feature where a port is specified, for example outbound messages, AJAX proxy, or single-sign on. <!-- document id=dd0e0ebf5c7741d9cf7f2b99fdd18b11b6f9bb46c42b59595ff2e05dd82c9d47 url=/developer/current/en-us/platform/api-streaming/guides/api-streaming/using/pushtopics/security-pushtopic-query.md --> # Security and the PushTopic Query Subscribers receive notifications about records that were created, updated, deleted, or undeleted if they have: - Field-level security access to the fields specified in the `WHERE` clause - Read access on the object in the query - Read access on the PushTopic - Visibility of the new or modified record based on sharing rules If the subscriber doesn’t have access to fields referenced in the query SELECT clause, then those fields aren’t included in the notification. If the subscriber doesn’t have access to all fields referenced in the query WHERE clause, then they don’t receive the notification. In addition to the field permissions that the subscriber must have, the user who creates or manipulates the record, which causes the notification to be generated, must have sufficient permissions to the fields in the SELECT clause. Otherwise, the notification that the subscriber receives doesn't include the fields the user doesn't have access to even if the subscriber has access to them. For example, assume a user tries to subscribe to a PushTopic with this `Query` value. ```soql SELECT Id, Name, SSN__c FROM Employee__c WHERE Bonus_Received__c = true AND Bonus_Amount__c > 20000 ``` If the subscriber doesn't have access to `Bonus_Received__c` or `Bonus_Amount__c`, the subscription fails. If the subscriber doesn’t have access to `SSN__c`, then it isn’t returned in the notification. If the subscriber has access to the SSN__c field but the user who created or manipulated the record doesn't, the subscriber doesn't receive this field in the notification. If the subscriber already successfully subscribed to the PushTopic, but the field-level security changes and the user no longer has access to one of the fields referenced in the WHERE clause, then no streamed notifications are sent. <!-- document id=cec87c5f2ef401f08f7c577807592cf74dd6bfa106882c73b01cc4b3c9b7d24b url=/developer/current/en-us/platform/change-data-capture/guides/change-data-capture/cdc-security-considerations.md --> # Security Considerations Learn about the user permissions required for subscription, field-level security, and Shield Platform Encryption. - **[Required Permissions for Change Event Subscribers](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-security-perms.md)** Change Data Capture ignores sharing settings and sends change events for all records of a Salesforce object. To receive change events on a channel, the subscribed user must have one or more permissions depending on the entities associated with the change events. The permissions apply to Pub/Sub API and CometD subscribers but not to Apex triggers. Apex triggers run with system privileges under the Automated Process entity, so they don’t require those permissions. - **[Field-Level Security](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-security-field.md)** Change Data Capture respects your org’s field-level security settings. Delivered events contain only the fields that a subscribed user is allowed to view. Before delivering a change event for an object, the subscribed user’s field permissions are checked. If a subscribed user has no access to a field, the field isn’t included in the change event message that the subscriber receives. - **[Change Events for Encrypted Salesforce Data](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-security-shield-encryption.md)** If Salesforce record fields are encrypted with Shield Platform Encryption, changes in encrypted field values generate change events. Change events are stored in the event bus for up to three days. To ensure that the events stored in the event bus are encrypted and not in clear text, create an event bus tenant secret and enable encryption. <!-- document id=5e408c0375d08ef75f48b82bd12b4bd9b2ca2271540d0555d7a19f48ac4994cb url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/security/pages-security-tips-intro.md --> # Security Tips for Apex and Visualforce Development ## Understanding Security The powerful combination of Apex and Visualforce pages allows Lightning Platform developers to provide custom functionality and business logic to Salesforce or to create a new standalone product running inside the Lightning Platform. But as with any programming language, developers must be cognizant of potential security-related pitfalls. Salesforce has incorporated several security defenses in the Lightning Platform. But careless developers can still bypass the built-in defenses and then expose their applications and customers to security risks. Many of the coding mistakes a developer can make on the Lightning Platform are similar to general web application security vulnerabilities, while others are unique to Apex. To certify an application for AppExchange, it’s important for developers to learn and understand the security flaws described. For more information, see the Lightning Platform Security Resources page on Salesforce Developers. [https://developer.salesforce.com/page/Security](https://developer.salesforce.com/page/Security). ## Open Redirects Through Static Resources URL redirects automatically send a user to a different web page. Redirects are often used to guide navigation to a website, or refer multiple domain names belonging to the same owner to refer to a single website. Unfortunately for developers, attackers can exploit URL redirects when not implemented properly. Open redirect (also known as “arbitrary redirect”) is a common web application vulnerability where values controlled by the user determine where the app redirects. **note:** Open redirects through static resources can expose users to the risk of unintended, and possibly malicious, redirects. Only admins with “Customize Application” permissions can upload static resources within an organization. Admins with this permission must use caution to ensure that static resources don’t contain malicious content. To learn how to help guard against static resources that were obtained from third parties, see [Referencing Untrusted Third-Party Content with iframes ](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_resources_iframe.htm) . - **[Cross Site Scripting (XSS)](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-security-tips-xss.md)** - **[Unescaped Output and Formulas in Visualforce Pages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-security-tips-scontrols.md)** When using components that have set the `escape` attribute to false, or when including formulas outside of a Visualforce component, output is unfiltered and must be validated for security. This is especially important when using formula expressions. - **[Cross-Site Request Forgery (CSRF)](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-security-tips-csrf.md)** - **[SOQL Injection](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-security-tips-soql-injection.md)** - **[Data Access Control](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-security-tips-data-access-control.md)** The Salesforce Platform makes extensive use of data sharing rules. Each object has permissions and can have sharing settings that users can read, create, edit, and delete. These settings are enforced when using all standard controllers. <!-- document id=ae8d039771838e6b3ffd696433103705fb31398e2644a26916796e75a7da497c url=/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-soql-select-fields.md --> # SELECT SOQL query syntax consists of a required `SELECT` statement that specifies the fields to query. The `fieldList` in the `SELECT` statement specifies the list of one or more fields, separated by commas, that you want to retrieve. ```soql SELECT fieldList [subquery][...] ``` Use the `FIELDS()` keyword in the `fieldList` to select groups of fields without knowing their names in advance. This keyword simplifies SELECT statements, avoids the need for multiple API calls, and provides a low-code method to explore the data in your org. This keyword is available in API version 51.0 and later. Using a field list in a SOQL SELECT statement (for example, `SELECT Id, Name FROM Account`) can be complicated if you need to retrieve many fields. And if you don’t know what fields an object has, you must first get a description of the object. Typically, you use a call to first get a description of the object, then parse the description to identify the fields. Then you construct a SOQL query that specifies the fields, and then make another call to submit the query. To simplify this process, the `FIELDS()` keyword lets you select fields easily, without knowing their names in advance. The `FIELDS()` keyword eliminates the need for a round trip to the server to prepare a SOQL statement, simplifies query statements, and makes it much easier to explore the shape of your objects. It also helps avoid exceeding the character limits on SOQL queries and the URI length limit for REST calls. You can include any of these in the field list: - `FIELDS(ALL)`—select all the fields of an object. - `FIELDS(CUSTOM)`—select all the custom fields of an object. - `FIELDS(STANDARD)`—select all the standard fields of an object. In each case, `FIELDS()` respects field-level security so it only shows the fields that you have permission to access. ## Usage You can use `FIELDS()` as the complete field list. For example: - `SELECT FIELDS(ALL) FROM Account LIMIT 200` - `SELECT FIELDS(CUSTOM) FROM Account LIMIT 200` - `SELECT FIELDS(STANDARD) FROM Account` You can also use `FIELDS()` with other field names in the field list. For example: - `SELECT Name, Id, FIELDS(CUSTOM) FROM Account LIMIT 200` - `SELECT someCustomField__c, FIELDS(STANDARD) FROM Account` The `FIELDS()` keyword can also be used in subqueries. For example: ```soql SELECT Account.Name, (SELECT FIELDS(ALL) FROM Account.Contacts LIMIT 200) FROM Account ``` The API returns an error if the `SELECT` statement results in any duplicated field names. For example, this query: ```soql SELECT Id, FIELDS(ALL) FROM User LIMIT 200 ``` gives this error: ```soql HTTP/1.1 400 Bad Request [ { "message" : "duplicate field selected: Id", "errorCode" : "INVALID_FIELD" } ] ``` ## Support for FIELDS() The `FIELDS()` keyword is supported in these platform features. - Apex - The SOQL language wherever query or queryAll operations can be executed. - Query jobs in Bulk API 2.0. - The Salesforce CLI. - The /query and /queryAll resources in the Lightning Platform REST API. - The query() and queryAll() operations in the Lightning Platform SOAP API. When building SOAP API integrations, take care when adopting `FIELDS()` with grouping options `STANDARD`, `CUSTOM`, and `ALL`.Any change to an org’s object model (such as admin modification, feature enablement, or update via major release) must be immediately reflected in the enterprise WSDL. Otherwise, an error is thrown as the query operation returns a result that doesn’t match the contract with the client. ## Bounded and Unbounded Queries The API distinguishes _bounded_ queries, which have well-defined sets of fields, from _unbounded_ queries, which have sets of fields that the API can’t determine in advance. For example, because the number of custom fields for an object isn’t predetermined, `FIELDS(CUSTOM)` and `FIELDS(ALL)` are considered unbounded. This table shows the support for `FIELDS()` in bounded and unbounded queries: | | Bounded – FIELDS(STANDARD) | Unbounded – FIELDS(ALL) and FIELDS(CUSTOM) | | | | ------------------------- | -------------------------- | ---------------------------------------------- | --- | --- | | Apex (inline and dynamic) | Supported | Not supported |   |   | | Bulk API 2.0 | Supported | Not supported |   |   | | CLI | Supported | Supported only if the result rows are limited. |   |   | | SOAP API and REST API | Supported | Supported only if the result rows are limited. |   |   | ## Limiting Result Rows To limit the result rows, you can add any of these limits to the query: - `LIMIT n` where `n` is less than or equal to 200. For example: ```soql SELECT FIELDS(ALL) FROM Contact LIMIT 200 ``` - `WHERE Id IN idList` where `idList` is list of up to 200 IDs. For example: ```soql SELECT FIELDS(ALL) FROM Contact WHERE Id IN ('003R000000ATjnCIAT', '003R000000AZFUIIA5', '003R000000DkYoFIAV') ``` - `WHERE Id IS idList` where `idList` is a list of up to 200 ID tests joined with boolean operators. For example: ```soql SELECT FIELDS(ALL) FROM Contact WHERE Id = '003R000000ATjnCIAT' OR Id = '003R000000AZFUIIA5' OR Id = '003R000000DkYoFIAV' ``` ## Salesforce CLI Example This example uses `FIELDS()` with the Salesforce CLI: ```soql sf data query --target-org DevHub --query "SELECT FIELDS(STANDARD) FROM Account" ``` This example assumes that the CLI is updated to work with version 51.0 or later of the API. ## REST API Example This request uses `FIELDS()` with /query in REST API: ```soql GET https://yourInstance.salesforce.com/services/data/v68.0/query?​q=SELECT+FIELDS(STANDARD)+FROM+Account ``` ## SOAP API Example This example uses `FIELDS()` with query() in SOAP API: ```soql POST https://yourInstance.salesforce.com/services/Soap/c/68.0 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com"> <soapenv:Header> <urn:SessionHeader> <urn:sessionId>sessionId</urn:sessionId> </urn:SessionHeader> </soapenv:Header> <soapenv:Body> <urn:query> <urn:queryString>SELECT FIELDS(STANDARD) FROM Account</urn:queryString> </urn:query> </soapenv:Body> </soapenv:Envelope> ``` ## Bulk API 2.0 Example This request uses `FIELDS()` when creating a bulk query job: ```soql POST https://yourInstance.salesforce.com/services/data/v68.0/jobs/query { "operation": "query", "query": "SELECT FIELDS(STANDARD) FROM Account" } ``` ## Considerations for FIELDS() Keep these considerations in mind when using the `FIELDS()` keyword. - If you already know which fields you want to retrieve, you’ll get better performance by specifying them explicitly rather than using `FIELDS()` and retrieving more fields than you need. - `FIELDS()` can cause errors if you use it with operators that require aggregation. - For example, without `FIELDS()` this query works correctly: `SELECT Id, MIN(NumberOfEmployees) FROM Account GROUP BY Id` But adding `FIELDS()` to the query `SELECT FIELDS(ALL), MIN(NumberOfEmployees) FROM Account GROUP BY Id LIMIT 200` results in a “Field must be grouped or aggregated” error because it’s equivalent to `SELECT IsDeleted, <etc.>,MIN(NumberOfEmployees) FROM Account GROUP BY Id LIMIT 200`. - If `FIELDS()` returns a large amount of data, use one of these methods to retrieve all the pages of results: - In SOQL, if you use OFFSET and LIMIT in your query, the number of records returned may be less than LIMIT. Check the number of results that were returned and adjust OFFSET, as required. Do not just increment OFFSET by LIMIT. - In Bulk API 2.0, use the Sforce-Locator response header that is returned in the job’s results. - In REST API, use the nextRecordsUrl that is returned by /query and /queryAll. - In SOAP API, use queryMore(). - If you use `SELECT FIELDS(CUSTOM)` on an object that doesn’t have any custom fields, the query results in an error. ```soql HTTP/1.1 400 Bad Request [ { "message": "'FIELDS(...)' expansion function must result in at least one field being selected.", "errorCode" : "MALFORMED_QUERY" } ] ``` If there are any fields included in the field list , there’s no error. For example, this query returns status code 200 even if the object contains no custom fields. ```soql SELECT Id, FIELDS(CUSTOM) FROM User LIMIT 200 ``` - The list of fields returned by `FIELDS()` reflects the current state of the org's metadata and data model. Any changes to your org’s metadata or data model affects query performance and results. <!-- document id=7c36da2648030e305c8c47ffabafb9ca060e8524ee58fa1c3c970c4221e90826 url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/dx/dx-onboard-wizard-landing.md --> # Select a Landing Page Template The Landing Page is the Mobile Offline home page for the Salesforce Mobile App. When a user logs into the Salesforce Mobile App offline experience, the landing page is the first thing they see. This page is intended to give access to the user’s most important records and allow them to quickly and easily take relevant actions. The landing page can be customized to meet user needs, using both out-of-the-box and custom objects, and Lightning global quick actions. It’s configured as a static resource file in JSON format. ![Landing page](https://developer.salesforce.com/media/mobile-offline/dx_onboard_landing.png) **note:** Only one landing page layout is allowed per org. ## Landing Page Templates You can use the Onboarding Wizard to select a preconfigured landing page template that best fits your use case. The Onboarding Wizard copies the landing page JSON file (based on the chosen template) into the Offline App Starter Kit `staticresources` folder. Locate and update the `landing_page.json file` to build a customized offline app experience. ![Landing page template picker](https://developer.salesforce.com/media/mobile-offline/dx_onboard_template_picker.png) Each landing page template has specific objects and quick actions. - Default - Accounts - Contacts - Opportunities - Case Management - New Case action - 5 most recent Cases - 5 most recent Accounts - 5 most recent Contacts - Healthcare - BarcodeScanner action - New Visit action - New Visitor action - Visit object - Retail Execution - New Opportunity action - New Lead action - New Account action For more information on updating the `landing_page.json` file, see [Customize The Landing Page](https://help.salesforce.com/s/articleView?language=en_US&id=sf.salesforce_app_plus_offline_landing_page.htm&type=5) in the Salesforce Help. <!-- document id=326f1d30f58e72c3f9e9ee0b06c6615a1fc6ef8cb7664bf9a4843dc47abd066a url=/developer/current/en-us/platform/change-data-capture/guides/change-data-capture/cdc-select-objects.md --> # Select Objects for Change Notifications in the User Interface To receive notifications on the default standard channel for record changes, select the custom objects and supported standard objects that you’re interested in on the Change Data Capture page. |User Permissions Needed| | |-----------------------|--| |**To view the Change Data Capture page:**|View Setup and Configuration| |**To add or modify entity selections:**|Customize Application| From Setup, in the Quick Find box, enter `Change Data Capture`, and click **Change Data Capture**. The Available Entities list shows the objects available in your Salesforce org for Change Data Capture. You can select up to five entities, including standard and custom objects. To enable more entities, contact your Salesforce Account Representative to purchase an add-on license. The add-on license removes the limit on the number of entities you can select. Also, it increases the event delivery allocation for CometD and Pub/Sub API clients. With the add-on license, you can select up to 10 entities at a time in the Available Entities list. After selecting the first 10 entities, you can add more. **note:** The Change Data Capture page shows the object selections for the default standard channel. It doesn’t show the selections for custom channels. See [Compose Streams of Change Data Capture Notifications with Custom Channels](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-custom-channel.md). Each list entry is in the format “Entity Label (API Name).” Because an entity label can be renamed, the API name is provided in parentheses to better identify the entity. ![Change Data Capture page with a list of available entities to enable](https://developer.salesforce.com/media/change-data-capture/cdc_selection_page.png) **See Also** - [Change Data Capture Allocations](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-allocations.md) <!-- document id=657792692c29420fe13e62a82ac5266f98af8b8362688c34043a439e82468703 url=/developer/current/en-us/platform/change-data-capture/guides/change-data-capture/cdc-object-selections-metadata.md --> # Select Objects for Change Notifications with Metadata API and Tooling API Use PlatformEventChannelMember in Metadata API or Tooling API to create or retrieve object event selections for the default standard channel or a custom channel. The default standard channel, ChangeEvents, corresponds to the selections that you configure in Setup in the Change Data Capture page. For a custom channel, the selections are set when you create the channel member. The `SelectedEntity` field in PlatformEventChannelMember represents a selected event. **note:** Selections made in PlatformEventChannelMember for a custom channel aren’t reflected in the Change Data Capture page. The Change Data Capture page shows selections only for the default standard channel, ChangeEvents, and not for custom channels. To find out which entities are selected for custom channels, perform a SOQL query on [PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannelmember.htm) in Tooling API. To learn how to select objects with Metadata API, see [PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannelmember.htm) in the [*Metadata API Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_intro.htm). To learn how to select objects with Tooling API, see [PlatformEventChannelMember](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannelmember.htm) in the [*Tooling API Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/intro_api_tooling.htm). To learn about custom channels, see [Compose Streams of Change Data Capture Notifications with Custom Channels](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-custom-channel.md), [PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_platformeventchannel.htm) in the [*Metadata API Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_intro.htm), and [PlatformEventChannel](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_platformeventchannel.htm) in the [*Tooling API Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/intro_api_tooling.htm). Starting with API version 47.0, you define channel member components and channels separately in Metadata API. In API version 45.0 and 46.0, members are included in the PlatformEventChannel component. **See Also** - [Change Data Capture Allocations](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-allocations.md) <!-- document id=1d51f237f25cce00a9b2d9a6312cd197965a803cc2e063ee7ca6528f1096a6fd url=/developer/current/en-us/platform/case_feed_dev_guide/guides/quickactions/quickaction-api-selectaction.md --> # selectAction Allows custom components to select and focus on a quick action on a record page. ## Arguments |Name|Type|Description| |----|----|-----------| |actionName|string|The name of the quick action that you want to access.| The actionName parameter starts with the Salesforce object, followed by the quick action name. For example: ```nolang actionName: "Case.UpdateCase" ``` ## Response Returns a Promise. Success resolves to a response object. The Promise is rejected on error response. ```nolang success: boolean, unavailableAction: boolean, targetableFields: [{ fieldName: "Status", type: "PickList" }], actionName: string, errors: [] ``` <!-- document id=00463769d98355f341c9509d78cb55a1238960fdf9a4b75cb219dc9168f0b4dc url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-send-conversation-messages.md --> # Send Conversation Messages Actions Send a messaging component to users in enhanced WhatsApp, enhanced Facebook, enhanced Apple Messages for Business, enhanced SMS, or Enhanced In-App Chat when the targeted channel has bandwidth. Each Send Conversation Messages action corresponds to a supported messaging component. This object is available in API version 59.0 and later. On invocation, this action inserts and enqueues a message for handling the request and sending out the messages async. The request record can be used to track the progress. Typical use cases include: - Confirmation of a purchase or booking - Shipping or delivery updates - Password reset requests - Account verification messages - Payment reminders - Abandoned cart reminders Messages are sent immediately as long as the following conditions are met. If these conditions aren't met, messages can be queued for sending, resulting in a slight delay. - The invocation of the Send Conversation Messages action includes 5 or fewer messages. If it includes more, the additional messages are queued. - No more than 200 invocations of the Send Conversation Messages action are in progress. If this limit is reached, additional requests are queued and sent when the number of in-progress requests falls below 200. For queued requests, the messaging session owner for automated messages is the Platform Integration User. Otherwise, it's the user triggering the action. - The conversation platform has the capacity available to send the message. Messages in active conversations are always prioritized over automated outbound messages. ## Supported REST HTTP Methods **URI:** `/services/data/v59.0/actions/standard/sendConversationMessages` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`allowedSessionStatus`|string|Limits the time when the message can be sent. Use `Any` to send the message whether the messaging user is engaged in a session or not. Use `NonActive` to send the message unless the user is in an Active session (the message is sent after the status changes). Use `Closed` to send the message only after the session is closed.| |`channelConsentType`|string|How to apply consent preferences when determining which messaging users receive the message. Use `MessagingEndUser` to apply messaging users' consent settings for a channel (most common approach). Use `CommunicationSubscription` to send only to users who opted into a particular subscription (requires `communicationSubscriptionId`; visible only if you have a unified channel that supports marketing interactions). Use `Custom` to apply custom consent preferences when `isEnforceMessagingChannelConsent` is `false`.| |`communicationSubscriptionId`|string|Available if `channelConsentType` is set to `CommunicationSubscription`. The subscription that controls which messaging users the message is sent to. The subscription must be tied to the channel where the message is sent, and the message is sent only to users who opted in to the subscription.| |`isEnforceMessagingChannelConsent`|boolean|Indicates whether messaging consent must be verified after messages are queued for sending.| |`messageDefinitionName`|string|The API name of a ConversationMessageDefinition (messaging component) record that's used to render the messages.| |`messagingDefinitionInputParameters`|list|Optional. A collection of Apex `richmessaging__MessageDefinitionInputParameter` records that contain messaging component details to use when rendering messages.| |`messagingEndUserIds`|list|A collection of up to 100 messaging end user record IDs to use as recipients of the messages. To send more than 100 messages, divide your end user recipients into batches of 100 or fewer and repeat the action invocation for each batch.| |`requestType`|string|Specifies the type of the request. Valid value: `SendNotificationMessages`.| ## Outputs |Output|Type|Description| |------|----|-----------| |`requestId`|string|The ID of the ConvMessageSendActionRequest record created by the request that's used to track the message progress.| |`messageIdentifiers`|list|A collection of generated message UUIDs with one entry for each recipient specified in messagingUserIds.| ## Usage **Sample Input** The following sample input attempts to create a ConvMessageSendRequest record using a Messaging Component (`messageDefinitionName`), the request for the type of component being sent (`requestType`), the consent preferences (`isEnforceMessagingChannelConsent`), the consent type (`channelConsentType`), when the message can be sent (`allowedSessionStatus`), and the message recipients (`messagingEndUserIds`). Additionally, the request contains a list of custom parameters (`messagingDefinitionInputParameters`). These parameters are mapped to parameters configured in the messaging component, which can be optional. Applicable data types for parameters are `textValue`, `recordIdValue`, `dateValue`, `dateTimeValue`, `numberValue`, and `booleanValue`. ```apex { "inputs": [{ "messageDefinitionName":"Notification", "requestType":"SendNotificationMessages", "isEnforceMessagingChannelConsent":true, "channelConsentType":"MessagingEndUser", "allowedSessionStatus":"Any", "messagingEndUserIds":"0PARM000000Lc3I,0PARM000000MZ3p", "messagingDefinitionInputParameters":[{"name":"custom_parameter_name","textValue":"custom parameter value"}] }] } ``` **Sample Output** The following sample output illustrates a response after a successful request. ```apex [ { "actionName":"sendConversationMessages", "errors":null, "isSuccess":true, "outputValues":{ "messageIdentifiers":"c581098c-5db6-4ed8-915f-c9aaa016c671,d8e1990e-5d67-414c-9713-180107d7d1bb", "requestId":"1srM000000000p" } } ] ``` For more information about this action, see [Flow Core Actions: Send Conversation Messages](https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_sendconversationmessages.htm&type=5) and [Send Automated Messages in Enhanced Messaging Channels](https://help.salesforce.com/s/articleView?id=service.messaging_automated_enhanced.htm&type=5) in Salesforce Help. <!-- document id=afdedac5a5c0ed26239f213d5ed6755f0472f5ed16d9b643b36c9df290b81a4a url=/developer/current/en-us/platform/api-rest/guides/resources/resources-composite-composite-post.md --> # Send Multiple Requests Using Composite Executes a series of REST API requests in a single call. You can use the output of one request as the input to a subsequent request. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire series of requests counts as a single call toward your API limits. **note:** The sObject Blob Get and sObject Rich Text Image Get APIs return binary data. These APIs aren’t supported in a Composite API request. The requests in a composite call are called subrequests. All subrequests are executed in the context of the same user. In a subrequest’s body, you specify a reference ID that maps to the subrequest’s response. You can then refer to the ID in the `url` or `body` fields of later subrequests by using a JavaScript-like reference notation. For example, the following composite request body includes two subrequests. The first creates an account and designates the output as `refAccount`. The second creates a contact parented under the new account by referencing `refAccount` in the subrequest body. ```nolang { "compositeRequest" : [{ "method" : "POST", "url" : "/services/data/v68.0/sobjects/Account", "referenceId" : "refAccount", "body" : { "Name" : "Sample Account" } },{ "method" : "POST", "url" : "/services/data/v68.0/sobjects/Contact", "referenceId" : "refContact", "body" : { "LastName" : "Sample Contact", "AccountId" : "@{refAccount.id}" } }] } ``` You can specify whether an error in a subrequest causes the whole composite request to roll back or just the subrequests that depend on it. You can also specify headers for each subrequest. Composite is supported for the following resources. - All sObject resources (`/services/data/vXX.X/sobjects/`), including [sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert.md) and excluding [sObject Blob Get](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-blob-retrieve.md) - The Query resource (`/services/data/vXX.X/query/?q=soql`) - The QueryAll resource (`/services/data/vXX.X/queryAll/?q=soql`) - The sObject Collections resource (`/services/data/vXX.X/composite/sobjects`). Available in API version 43.0 and later. **note:** You can have up to 25 subrequests in a single call. Up to 5 of these subrequests can be sObject Collections or query operations, including Query and QueryAll requests. ## Syntax **URI:** `/services/data/vXX.X/composite` **Formats:** JSON **HTTP method:** POST **Authentication:** `Authorization: Bearer token` **Parameters:** None required **Request body:** [Composite Request Body](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-composite.md) **Response body:** [Composite Response Body](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-composite.md) ## Example For examples of using the Composite resource, see [Execute Dependent Requests in a Single API Call](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-composite-record-manipulation.md) and [Update an Account, Create a Contact, and Link Them with a Junction Object](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-composite-junction-object.md). - **[Composite Subrequest Result](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-composite-subrequest-result.md)** The composite subrequest result describes the result for a subrequest. <!-- document id=4932662c86f5b41d058e0903cb986bebf6949c378046ac440fc026e465b5633c url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-send-notification.md --> # Send Notification Actions Call a notification type to send. Each Send Notification action corresponds to a supported notification type. This object is available in API version 54.0 and later. Send Notification actions are available only for Slack-enabled custom notification types and certain Slack-enabled standard notification types. To send notifications for Slack, enable [Salesforce for Slack Integrations](https://help.salesforce.com/s/articleView?id=slack.slack_apps_enable.htm&type=5). To create a custom Slack notification type supported by a Send Notification action, see [Create and Send Custom Slack Notifications](https://help.salesforce.com/s/articleView?id=platform.notif_builder_create_send_slack.htm&type=5). To trigger Send Notification actions using REST API calls, you need the Send Custom Notifications user permission. ## Supported REST HTTP Methods **URIs:** - Get a list of available Send Notification actions: `/services/data/vXX.X/actions/custom/sendNotification` - Get information about a specific Send Notification action: `/services/data/vXX.X/actions/custom/sendNotification/notification_type_name` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`recipientIds`|ID|Required. The IDs of the notification recipients or recipient types. Valid recipient or recipient type values are UserId or CollaborationRoomId values.| |`recordId`|ID|Required. The ID of the record that the notifications are about. The record ID must be associated with the specific EntityType of the notification type. For example, enter the record ID for an opportunity when configuring a notification type associated with the Opportunity object. For custom notification types, you can find the related object by viewing the notification type's settings from Custom Notifications in Setup. For supported standard notification types, refer to the Standard Notification Types and Related Objects table.| ## Standard Notification Types and Related Objects Use this table to identify which object applies to each standard notification type supported by a Send Notification action. The object determines the value that you enter for `recordId`. |Standard Notification Type|Related Salesforce Object| |--------------------------|-------------------------| |`amount_updated`|Opportunity| |`close_date_reminder`|Opportunity| |`close_date_updated`|Opportunity| |`deal_won`|Opportunity| |`deals_to_watch`|Opportunity| |`hc_allergy_intolerance_alert`|Allergy Intolerance| |`hc_care_determinant_alert`|Care Determinant| |`hc_care_plan_alert`|Case| |`hc_care_plan_task_alert`|Task| |`hc_health_condition_alert`|Health Condition| |`high_priority_case`|Case| |`new_child_opportunity`|Opportunity| |`next_step_reminder`|Opportunity| |`stage_reminder`|Opportunity| |`stage_updated`|Opportunity| **See Also** - [*Object Reference for the Salesforce Platform*: CollaborationRoom](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_collaborationroom.htm) - [*Object Reference for the Salesforce Platform*: Swarm](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_swarm.htm) <!-- document id=98f2694423cec4e843b965d700b454b0c940118250b22579eec206c26255066a url=/developer/current/en-us/platform/api-rest/guides/intro/intro-curl.md --> # Send REST Requests with cURL The examples in this guide use the cURL tool to send HTTP requests that access, create, and manipulate resources in Salesforce. If you use a different tool to send requests, you can use the same elements from the cURL examples to send requests. cURL is pre-installed on many Linux and macOS systems. Windows users can download a version at [curl.haxx.se/](http://curl.haxx.se/). When using HTTPS on Windows, ensure that your system meets the cURL requirements for SSL. **note:** cURL is an open-source tool and isn’t supported by Salesforce. ## Attaching Request Bodies Many examples include request bodies—JSON or XML files that contain data for the request. When using cURL, save these files to your local system and attach them to the request using the —data-binary or -d option. This example attaches the new-account.json file. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v/sobjects/Account/ -H "Authorization: Bearer access-token" -H “Content-Type: application/json” —data-binary @new-account.json -X POST ``` ## Handling Exclamation Marks in Access Tokens When you run cURL examples, you can get an error on macOS and Linux systems due to the presence of the exclamation mark (!) special character in OAuth access tokens. To avoid getting this error, either escape the exclamation mark or use single quotes. To escape the exclamation mark in the access token, insert a backslash before it (\\!) when the access token is enclosed within double quotes. For example, the access token string in this cURL command has the exclamation mark (!) escaped. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/ -H "Authorization: Bearer 00DE0X0A0M0PeLE\!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE" ``` Or, you can enclose the access token within single quotes. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' ``` **See Also** - [Setting Up Your Java Developer Environment](https://developer.salesforce.com/docs/atlas.en-us.salesforce_developer_environment_tipsheet.meta/salesforce_developer_environment_tipsheet/salesforce_developer_environment_overview.htm) <!-- document id=40aeaf8c815c8e985d9e7813f23dd1b6e97059a3808ed4860df3cf202accae41 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-send-survey-invitation.md --> # Send Survey Invitation Actions Send email survey invitations to leads, contacts, and users in your org based on an action. For example, send a survey invitation when a customer support case closes. This action is available in API version 47.0 and later. ## Special Access Rules To access the Send Survey Invitation action, you must have the Feedback Management Survey Response Pack and the Salesforce org enabled with Surveys. ## Supported REST HTTP Methods **URI:** `/services/data/v47.0/actions/standard/sendSurveyInvitation` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`anonymousResponse`|boolean|Indicates whether the participant's name is recorded in the response record (`true`) or not (`false`).| |`autoExpiryDays`|integer|Number of days remaining for the survey invitation to expire.| |`emailTemplateName`|string|Developer name of the template that contains either the question or the survey link.| |`isUnauthenticatedResponse`|boolean|Indicates whether the participant is required to authenticate before starting the survey (`true`) or not (`false`).| |`personalInvitation`|boolean|Indicates whether the invitation is specific to the recipient (`true`) or not (`false`).| |`recipient`|reference|Required. Salesforce ID of the record that the survey invitation is sent to. The record can be a user (internal invitation) or a contact or a lead (external invitation via community).| |`surveyName`|string|Required. Developer name of the survey that the invitation is sent for.| |`surveyQuestionName`|string|Developer name of the question that's sent using the invitation.| |`surveySubjectEntity`|reference|ID of the record that associates the invitation record with another record.| ## Outputs None. ## Example **GET** This example shows how to get information about the Send Survey Invitation action type. ```nolang curl --include --request GET \ --header "Authorization: Authorization: Bearer 00DR...xyz" \ --header "Content-Type: application/json" \ "https://instance.salesforce.com/services/data/v47.0/actions/standard/sendSurveyInvitation" ``` **POST** Here's a request for the send survey invitation action. ```nolang { "inputs":[{ "surveyName" : "FlowActionSend", "recipient" : "003RO0000037IRvYAM", "autoExpiryDays" : 6 }] } ``` Here's a response for the send survey invitation action. ```nolang [ { "actionName" : "sendSurveyInvitation", "errors" : null, "isSuccess" : true, "outputValues" : null } ] ``` **See Also** - [*Salesforce Help*: Send Survey Invitations Using Process Builder](https://help.salesforce.com/s/articleView?id=platform.process_action_send_survey_invite.htm&type=5) <!-- document id=e39a0901a2bdba0723e52bab8c313e739d173cc8c7acad8cb4de53587bbde5d2 url=/developer/current/en-us/platform/api/guides/api/utils/sforce-api-calls-sendemail.md --> # sendEmail() Immediately sends an email message. ## Syntax For single email messages: ```java SendEmailResult = connection.sendEmail(SingleEmailMessage emails[]); ``` For mass email messages: ```java SendEmailResult = connection.sendEmail(MassEmailMessage emails[]); ``` ## Usage Use this call with Lightning Platform AppExchange applications, custom applications, or other applications outside of Salesforce to send individual and mass email. The email can include all standard email attributes (such as subject line and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format. You can use Salesforce to track the status of HTML email, including the date the email was sent, first opened, last opened, and the total number of times it was opened. (See “Tracking HTML Email” in Salesforce Help for more information.) The email address of the logged-in user is inserted in the `From Address` field of the email header. All return email and out-of-office replies go to the logged-in user. If bounce management is enabled and `SingleEmailMessage.targetObjectId` or `MassEmailMessage.targetObjectIds` is set, bounces are processed by Salesforce automatically, and the appropriate records are updated; otherwise, they go to the logged-in user. Bounce management works for contacts and leads only. **note:** - Single email messages sent with this call count against the sending organization's daily single email limit. When this limit is reached, `sendEmail()` calls using SingleEmailMessage are rejected, and the user receives a [`SINGLE_EMAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) error code. However, single emails sent through the application are allowed. - Mass email messages sent with this call count against the sending organization's daily mass email limit. When this limit is reached, `sendEmail()` calls using MassEmailMessage are rejected, and the user receives a [`MASS_MAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) error code. - Starting in API version 35.0, you can enforce or ignore the **Email Opt Out** setting for contacts or leads with the [`optOutPolicy`](#sendemail) field of `SingleEmailMessage`. The `optOutPolicy` field applies to recipients in the To, CC, and BCC lists of the email. By default and in earlier versions, `SingleEmailMessage` ignores the **Email Opt Out** setting of recipients and the email is sent to all recipients. When using `MassEmailMessage`, the **Email Opt Out** setting of the recipients is always enforced—emails aren’t sent to recipients that have opted out and are sent to all other recipients. SingleEmailMessage has an optional field called `OrgWideEmailAddressId`, an object ID to an [OrgWideEmailAddress](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_orgwideemailaddress.htm) object. If `OrgWideEmailAddressId` is set, the OrgWideEmailAddress `DisplayName` field is used in the email header, instead of the logged-in user's `Display Name`. The sending email address in the header is also set to the field defined in OrgWideEmailAddress.`Address`. **note:** If both the `DisplayName` in an OrgWideEmailAddress and `senderDisplayName` are defined, the user receives a [`DUPLICATE_SENDER_DISPLAY_NAME`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) error. ## Sample Code—Java This sample creates an email message and sets its fields, including the To, CC and BCC recipients, subject, and body text. It also sets a recipient to the ID of the logged-in user using the `setTargetObjectId` method, which causes the email to be sent to the email address of the specified user. The sample creates an attachment and sends the email message with the attachment. Finally, it writes a status message or an error message, if any, to the console. <!-- otherprops: java set_clipboard --> ```codesegment public void doSendEmail() { try { EmailFileAttachment efa = new EmailFileAttachment(); byte[] fileBody = new byte[1000000]; efa.setBody(fileBody); efa.setFileName("attachment"); SingleEmailMessage message = new SingleEmailMessage(); message.setBccAddresses(new String[] { "someone@salesforce.com" }); message.setCcAddresses(new String[] { "person1@salesforce.com", "person2@salesforce.com", "003xx00000a1b2cAAC" }); message.setBccSender(true); message.setEmailPriority(EmailPriority.High); message.setReplyTo("person1@salesforce.com"); message.setSaveAsActivity(false); message.setSubject("This is how you use the " + "sendEmail method."); // We can also just use an id for an implicit to address GetUserInfoResult guir = connection.getUserInfo(); message.setTargetObjectId(guir.getUserId()); message.setUseSignature(true); message.setPlainTextBody("This is the humongous body " + "of the message."); EmailFileAttachment[] efas = { efa }; message.setFileAttachments(efas); message.setToAddresses(new String[] { "person3@salesforce.com" }); SingleEmailMessage[] messages = { message }; SendEmailResult[] results = connection.sendEmail(messages); if (results[0].isSuccess()) { System.out.println("The email was sent successfully."); } else { System.out.println("The email failed to send: " + results[0].getErrors()[0].getMessage()); } } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` This example shows how to send an email with the opt-out setting enforced. Recipients are specified by their IDs. The `SendEmailOptOutPolicy.FILTER` option causes the email to be sent only to recipients that haven’t opted out from email. <!-- otherprops: java set_clipboard --> ```codesegment SingleEmailMessage message = new SingleEmailMessage(); // Set recipients to two contact IDs. // Replace IDs with valid record IDs in your org. message.setToAddresses(new String[] { "003D000000QDexS", "003D000000QDfW5" }); message.setOptOutPolicy(SendEmailOptOutPolicy.FILTER); message.setSubject("Opt Out Test Message"); message.setPlainTextBody("This is the message body."); SingleEmailMessage[] messages = { message }; SendEmailResult[] results = connection.sendEmail(messages); if (results[0].isSuccess()) { System.out.println("The email was sent successfully."); } else { System.out.println("The email failed to send: " + results[0].getErrors()[0].getMessage()); } ``` ## Sample Code—C# This sample creates an email message and sets its fields, including the To, CC and BCC recipients, subject, and body text. It also sets a recipient to the ID of the logged-in user using the `setTargetObjectId` method, which causes the email to be sent to the email address of the specified user. The sample creates an attachment and sends the email message with the attachment. Finally, it writes a status message or an error message, if any, to the console. <!-- otherprops: set_clipboard --> ```c_sharp public void doSendEmail() { try { EmailFileAttachment efa = new EmailFileAttachment(); byte[] fileBody = new byte[1000000]; efa.body = fileBody; efa.fileName = "attachment"; SingleEmailMessage message = new SingleEmailMessage(); message.setBccAddresses(new String[] { "someone@salesforce.com" }); message.setCcAddresses(new String[] { "person1@salesforce.com", "person2@salesforce.com", "003xx00000a1b2cAAC" }); message.bccSender = true; message.emailPriority = EmailPriority.High; message.replyTo = "person1@salesforce.com"; message.saveAsActivity = false; message.subject = "This is how you use the " + "sendEmail method."; // We can also just use an id for an implicit to address GetUserInfoResult guir = binding.getUserInfo(); message.targetObjectId = guir.userId; message.useSignature = true; message.plainTextBody = "This is the humongous body " + "of the message."; EmailFileAttachment[] efas = { efa }; message.fileAttachments = efas; message.toAddresses = new String[] { "person3@salesforce.com" }; SingleEmailMessage[] messages = { message }; SendEmailResult[] results = binding.sendEmail(messages); if (results[0].success) { Console.WriteLine("The email was sent successfully."); } else { Console.WriteLine("The email failed to send: " + results[0].errors[0].message); } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` This example shows how to send an email with the opt-out setting enforced. Recipients are specified by their IDs. The `SendEmailOptOutPolicy.FILTER` option causes the email to be sent only to recipients that haven’t opted out from email. <!-- otherprops: java set_clipboard --> ```codesegment SingleEmailMessage message = new SingleEmailMessage(); // Set recipients to two contact IDs. // Replace IDs with valid record IDs in your org. message.toAddresses = new String[] { "003D000000QDexS", "003D000000QDfW5" }; message.optOutPolicy = SendEmailOptOutPolicy.FILTER; message.subject = "Opt Out Test Message"; message.plainTextBody = "This is the message body."; SingleEmailMessage[] messages = { message }; SendEmailResult[] results = binding.sendEmail(messages); if (results[0].success) { Console.WriteLine("The email was sent successfully."); } else { Console.WriteLine("The email failed to send: " + results[0].errors[0].message); } ``` ## BaseEmail This table contains the arguments used in both single and mass email. **note:** If templates aren’t being used, all email content must be in plain text, HTML, or both. |Name|Type|Description| |----|----|-----------| |`bccSender`|boolean|Indicates whether the email sender receives a copy of the email that is sent. For a mass mail, the sender is only copied on the first email sent. If the BCC compliance option is set at the organization level, the user can’t add BCC addresses on standard messages. The following error code is returned: `BCC_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED`. Contact your Salesforce representative for information on BCC compliance.| |`saveAsActivity`|boolean|Optional. The default value is `true`, meaning the email is saved as an activity. This argument only applies if the recipient list is based on `targetObjectId` or `targetObjectIds`. If HTML email tracking is enabled for the organization, you can track open rates.| |`useSignature`|boolean|Indicates whether the email includes an email signature if the user has one configured. The default is `true`, meaning if the user has a signature it is included in the email unless you specify `false`.| |`emailPriority`|picklist|Optional. The priority of the email.<ul><li>Highest</li><li>High</li><li>Normal</li><li>Low</li><li>Lowest</li></ul>The default is Normal.| |`replyTo`|string|Optional. The email address that receives the message when a recipient replies. This argument can’t be set if you’re using a Visualforce email template that specifies a `replyTo` value.| |`subject`|string|Optional. The email subject line. If you’re using an email template and attempt to override the subject line, an error message is returned.| |`templateId`|ID|The ID of the template to be merged to create this email.| |`senderDisplayName`|string|Optional. The name that appears on the `From` line of the email. This argument can’t be set if the object associated with a `OrgWideEmailAddressId` for a SingleEmailMessage has defined its `DisplayName` field.| ## SingleEmailMessage The following table contains the arguments single email uses in addition to the base email arguments. <sfdocstbl><table> <col> </col> <col> </col> <col> </col> <thead> <tr> <th> Name </th> <th> Type </th> <th> Description </th> </tr> </thead> <tbody> <tr> <td> <code>bccAddresses</code> </td> <td> string[] </td> <td> Optional. An array of blind carbon copy (BCC) addresses or object IDs of the contacts, leads, and users you’re sending the email to. This argument is allowed only when a template isn’t used. The maximum size for this field is 4,000 bytes. The maximum total of <code>toAddresses</code> , <code>ccAddresses</code> , and <code>bccAddresses</code> per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. <p> You can specify opt-out email options with the <code>optOutPolicy</code> field only for those recipients who were added by their IDs. </p> <p> Email addresses are verified to ensure that they have the correct format and haven’t been marked as bounced. </p> <p> If the BCC COMPLIANCE option is set at the organization level, the user can’t add BCC addresses on standard messages. The following error code is returned: <a href="https://developer.salesforce.com/docs/platform/api/guide/sforce_api_calls_concepts_core_data_objects.md#statuscode"><code>BCC_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED</code></a> . </p> <p> All emails must have a recipient value in at least one of the following fields: </p> <ul> <li> <p> <code>toAddresses</code> </p> </li> <li> <p> <code>ccAddresses</code> </p> </li> <li> <p> <code>bccAddresses</code> </p> </li> <li> <p> <code>targetObjectId</code> </p> </li> </ul> </td> </tr> <tr> <td> <code>ccAddresses</code> </td> <td> string[] </td> <td> Optional. An array of carbon copy (CC) addresses or object IDs of the contacts, leads, and users you’re sending the email to. This argument is allowed only when a template isn’t used. The maximum size for this field is 4,000 bytes. The maximum total of <code>toAddresses</code> , <code>ccAddresses</code> , and <code>bccAddresses</code> per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. <p> You can specify opt-out email options with the <code>optOutPolicy</code> field only for those recipients who were added by their IDs. </p> <p> Email addresses are verified to ensure that they have the correct format and haven’t been marked as bounced. </p> <p> All emails must have a recipient value in at least one of these fields. </p> <ul> <li> <p> <code>toAddresses</code> </p> </li> <li> <p> <code>ccAddresses</code> </p> </li> <li> <p> <code>bccAddresses</code> </p> </li> <li> <p> <code>targetObjectId</code> </p> </li> </ul> </td> </tr> <tr> <td> <code>charset</code> </td> <td> string </td> <td> Optional. The character set for the email. If this value is null, the user's default value is used. Unavailable if specifying <code>templateId</code> because the template specifies the character set. </td> </tr> <tr> <td> <code>documentAttachments</code> </td> <td> ID[] </td> <td> <strong>Deprecated. Use<a href="#sendemail" title="Immediately sends an email message."><code>entityAttachments</code></a>instead.</strong> Optional. An array listing the ID of each <a href="https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_document.htm">Document</a> you want to attach to the email. </td> </tr> <tr> <td> <code>entityAttachments</code> </td> <td> ID[] </td> <td> Optional. Array of IDs of <a href="https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_document.htm">Document</a>, <a href="https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_contentversion.htm">ContentVersion</a>, or <a href="https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_attachment.htm">Attachment</a> items to attach to the email. <p> This field is available in API version 35.0 and later. </p> </td> </tr> <tr> <td> <code>fileAttachments</code> </td> <td> EmailFileAttachment[] </td> <td> Optional. An array listing the file names of the binary and text files you want to attach to the email. You can attach multiple files as long as the total size of all attachments doesn’t exceed 20 MB. </td> </tr> <tr> <td> <code>htmlBody</code> </td> <td> string </td> <td> Optional. The HTML version of the email, specified by the sender. The value is encoded according to the specification associated with the organization. </td> </tr> <tr> <td> <code>inReplyTo</code> </td> <td> string </td> <td> Optional. The In-Reply-To field of the outgoing email. Identifies the emails to which this one is a reply (parent emails). Contains the parent emails' Message-IDs. See <a href="http://www.faqs.org/rfcs/rfc2822.html">RFC2822 - Internet Message Format</a> . </td> </tr> <tr> <td> <code>optOutPolicy</code> </td> <td> SendEmailOptOutPolicy (enumeration of type string) </td> <td> Optional. If you add contact, lead, or person account recipients by ID instead of email address, this field determines the behavior of the <code>sendEmail()</code> call. By default, the opt-out settings for recipients added by their email addresses aren’t checked and those recipients always receive the email. Possible values of the <code>SendEmailOptOutPolicy</code> enumeration are: <ul> <li> <p> <code>SEND</code> (default)—The email is sent to all recipients. The recipients’ <code>Email Opt Out</code> setting is ignored. The setting Enforce email privacy settings is ignored. </p> </li> <li> <p> <code>FILTER</code> —No email is sent to recipients that have the <code>Email Opt Out</code> option set. Emails are sent to the other recipients. The setting Enforce email privacy settings is ignored. </p> </li> <li> <p> <code>REJECT</code> —If any of the recipients have the <code>Email Opt Out</code> option set, <code>sendEmail()</code> throws an error and no email is sent. The setting Enforce email privacy settings is respected, as are the selections in the data privacy record based on the Individual object. If any of the recipients have Don’t Market, Don’t Process, or Forget This Individual selected, <code>sendEmail()</code> throws an error and no email is sent. </p> </li> </ul> <p> The Send Non-Commercial Email permission isn’t respected. </p> <p> This field is available in API version 35.0 and later. </p> </td> </tr> <tr> <td> <code>orgWideEmailAddressId</code> </td> <td> ID </td> <td> Optional. The object ID of the OrgWideEmailAddress associated with the outgoing email. OrgWideEmailAddress. <code>DisplayName</code> can’t be set if the <code>senderDisplayName</code> field is already set. </td> </tr> <tr> <td> <code>plainTextBody</code> </td> <td> string </td> <td> Optional. The text version of the email, specified by the sender. </td> </tr> <tr> <td> <code>references</code> </td> <td> string </td> <td> Optional. The References field of the outgoing email. Identifies an email thread. Contains the parent emails' Message-ID and References fields and possibly In-Reply-To fields. See <a href="http://www.faqs.org/rfcs/rfc2822.html">RFC2822 - Internet Message Format</a> . </td> </tr> <tr> <td> <code>targetObjectId</code> </td> <td> ID </td> <td> Optional. The object ID of the contact, lead, or user the email is sent to. The object ID you enter sets the context and ensures that merge fields in the template contain the correct data <p> All emails must have a recipient value in at least one of these fields. </p> <ul> <li> <p> <code>toAddresses</code> </p> </li> <li> <p> <code>ccAddresses</code> </p> </li> <li> <p> <code>bccAddresses</code> </p> </li> <li> <p> <code>targetObjectId</code> </p> </li> </ul> </td> </tr> <tr> <td> <code>toAddresses</code> </td> <td> string[] </td> <td> Optional. An array of email addresses or object IDs of the contacts, leads, or users you’re sending the email to. This argument is allowed only when a template isn’t used. The maximum size for this field is 4,000 bytes. The maximum total of <code>toAddresses</code> , <code>ccAddresses</code> , and <code>bccAddresses</code> per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. <p> You can specify opt-out email options with the <code>optOutPolicy</code> field only for those recipients who were added by their IDs. </p> <p> Email addresses are verified to ensure that they have the correct format and haven’t been marked as bounced. </p> <p> All emails must have a recipient value in at least one of these fields. </p> <ul> <li> <p> <code>toAddresses</code> </p> </li> <li> <p> <code>ccAddresses</code> </p> </li> <li> <p> <code>bccAddresses</code> </p> </li> <li> <p> <code>targetObjectId</code> </p> </li> </ul> </td> </tr> <tr> <td> <code>treatBodiesAsTemplate</code> </td> <td> boolean </td> <td> Optional. If set to <code>true</code>, the subject, plain text, and HTML text bodies of the email are treated as template data. The merge fields are resolved using the <a href="https://developer.salesforce.com/docs/platform/api/guide/sforce_api_calls_renderemailtemplate.md" title="Replaces merge fields in text bodies of email templates with values from Salesforce records, even for polymorphic fields. The email template bodies and their corresponding whoId and whatId values are specified in the argument."><code>renderEmailTemplate()</code></a> call. Default is <code>false</code>. <p> This field is available in API version 35.0 and later. </p> </td> </tr> <tr> <td> <code>treatTargetObjectAsRecipient</code> </td> <td> boolean </td> <td> Optional. If set to <code>true</code>, the <code>targetObjectId</code> (a contact, lead, or user) is the recipient of the email. If set to <code>false</code>, the <code>targetObjectId</code> is supplied as the <code>WhoId</code> field for template rendering but isn’t a recipient of the email. The default is <code>true</code>. <p> This field is available in API version 35.0 and later. In prior versions, the <code>targetObjectId</code> is always a recipient of the email. </p> </td> </tr> <tr> <td> <code>whatId</code> </td> <td> ID </td> <td> Optional. If you specify a contact for the <code>targetObjectId</code> field, you can specify a <code>whatId</code> as well. This field helps to further ensure that merge fields in the template contain the correct data. The value must be one of the following types: <ul> <li> <p> <code>Account</code> </p> </li> <li> <p> <code>Asset</code> </p> </li> <li> <p> <code>Campaign</code> </p> </li> <li> <p> <code>Case</code> </p> </li> <li> <p> <code>Contract</code> </p> </li> <li> <p> <code>Opportunity</code> </p> </li> <li> <p> <code>Order</code> </p> </li> <li> <p> <code>Product</code> </p> </li> <li> <p> <code>Solution</code> </p> </li> <li> <p> <code>Custom</code> </p> </li> </ul> </td> </tr> </tbody> </table></sfdocstbl> ## MassEmailMessage The following table contains the arguments mass email uses in addition to the base email arguments. |Name|Type|Description| |----|----|-----------| |`description`|string|A value used internally to identify the object in the mass email queue.| |`targetObjectIds`|ID[]|An array of object IDs of the contacts, leads, or users the email is sent to. The object IDs you enter set the context and ensure that merge fields in the template contain the correct data. The objects must be of the same type (either all contacts, all leads, or all users). You can list up to 250 IDs per email. If you specify a value for the `targetObjectIds` field, optionally specify a `whatId` as well to set the email context to a user, contact, or lead. Specifying these IDs ensures that merge fields in the template contain the correct data.| |`whatIds`|ID[]|Optional. If you specify an array of contacts for the `targetObjectIds` field, you can specify an array of `whatIds` as well. Specifying these IDs ensures that merge fields in the template contain the correct data. The values must be one of these types.<ul><li>Contract</li><li>Case</li><li>Opportunity</li><li>Product</li></ul>If you specify `whatIds`, specify one for each `targetObjectId`; otherwise, you receive an [`INVALID_ID_FIELD`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) error.| ## EmailFileAttachment The following table contains properties that the EmailFileAttachment uses in the SingleEmailMessage object to specify attachments passed in as part of the request, as opposed to a [Document](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_document.htm) passed in using the `documentAttachments` argument. |Property|Type|Description| |--------|----|-----------| |`body`|base64|The attachment itself.| |`contentType`|string|Optional. The attachment's Content-Type.| |`fileName`|string|The name of the file to attach.| |`inline`|boolean|Optional. Specifies a Content-Disposition of inline (`true`) or attachment (`false`). In most cases, inline content is displayed to the user when the message is opened. Attachment content requires user action to be displayed.| ## Response [SendEmailResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail-emailresult.md) ## Fault The following API status codes can be returned. Also, `sendEmail()` can return other errors when rendering email templates. See [`renderEmailTemplate()` Faults](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-renderemailtemplate.md#fault). [`BCC_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`BCC_SELF_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`DUPLICATE_SENDER_DISPLAY_NAME`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`EMAIL_ADDRESS_BOUNCED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`EMAIL_NOT_PROCESSED_DUE_TO_PRIOR_ERROR`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`EMAIL_OPTED_OUT`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`ERROR_IN_MAILER`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_CONTENT_TYPE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_EMAIL_ADDRESS`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_ID_FIELD`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`INVALID_MESSAGE_ID_REFERENCE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_SAVE_AS_ACTIVITY_FLAG`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`MALFORMED_ID`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`MASS_MAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`NO_MASS_MAIL_PERMISSION`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`REQUIRED_FIELD_MISSING`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`SINGLE_EMAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`TEMPLATE_NOT_ACTIVE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`UNVERIFIED_SENDER_ADDRESS`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) <!-- document id=619bbd23a97d026b90afcfcc05793fc277df26724ff5a61d4f54556cd9f47a30 url=/developer/current/en-us/platform/api/guides/api/utils/sforce-api-calls-send-email-message.md --> # `sendEmailMessage()` Immediately sends up to 10 draft email messages. ## Syntax For Enterprise SOAP: ```nolang SendEmailResult[] = connection.sendEmailMessage( String[] draftEmailIds); ``` For Partner SOAP: ```nolang SendEmailResult[] = connection.sendEmailMessage( ID[] draftEmailIds); ``` ## Usage Use this call with Lightning Platform AppExchange applications, custom applications, or other applications outside of Salesforce to send up to 10 draft email messages. The messages can include all standard email attributes (such as subject line and blind carbon copy address), use Salesforce email templates, and be in plain text or HTML format. You can use Salesforce to track the status of HTML email, including the date the email was sent, first opened, last opened, and the total number of times it was opened. (See Tracking HTML Email in the Salesforce Help for more information.) The email address of the logged-in user is inserted in the `From Address` field of the email header. All return email and out-of-office replies go to the logged-in user. If bounce management is enabled and `SingleEmailMessage.targetObjectId` or `MassEmailMessage.targetObjectIds` is set, bounces are processed by Salesforce automatically, and the appropriate records are updated; otherwise, they go to the logged-in user. Bounce management works for contacts and leads only. **note:** - Email messages sent with this call count against the sending organization's daily single email limit. When this limit is reached, `sendEmailMessage()` calls using SingleEmailMessage are rejected, and the user receives a [`SINGLE_EMAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) error code. However, single emails sent through the application are allowed. - Mass email messages sent with this call count against the sending organization's daily mass email limit. When this limit is reached, `sendEmail()` calls using MassEmailMessage are rejected, and the user receives a [`MASS_MAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) error code. - The `AllOrNone` header is not honored by this call. `sendEmailMessage()` returns partial success even if the `AllOrNone` header is set to `true`. ## Sample Code—Java This sample creates a case and a draft email message, and sets the message fields, including the `From`, `To`, `CC`, and `BCC` recipients, subject, and body text. It also creates an attachment and sends the email message with the attachment. Finally, it writes a status message or an error message, if any, to the console. <!-- otherprops: java set_clipboard --> ```codesegment public void doSendEmail() { try { //Create a case Case theCase = new Case(); theCase.setSubject("Sample Case"); SaveResult[] saveResult = connection.create(new SObject[] { theCase }); String caseId = saveResult[0].getId(); //Create a draft EmailMessage EmailMessage message = new EmailMessage(); message.setParentId(theCase.getId()); message.setBccAddress("bcc@email.com"); message.setCcAddress("cc1@salesforce.com; cc2@email.com"); message.setSubject("This is how you use the sendEmailMessage method."); message.setFromAddress("from@email.com"); message.setFromName("Sample Code"); message.setTextBody("This is the text body of the message."); message.setStatus("5"); //"5" means Draft message.setToAddress("to@email.com"); saveResult = connection.create(new SObject[] { message }); String emailMessageId = saveResult[0].getId(); //Create an attachment for the draft EmailMessage Attachment att = new Attachment(); byte[] fileBody = new byte[1000000]; att.setBody(fileBody); att.setName("attachment"); att.setParentId(emailMessageId); connection.create(new SObject[] { att }); //Send the draft EmailMessage SendEmailResult[] results = connection.sendEmailMessage(messages); if (results[0].isSuccess()) { System.out.println("The email was sent successfully."); } else { System.out.println("The email failed to send: " + results[0].getErrors()[0].getMessage()); } } catch (ConnectionException ce) { ce.printStackTrace(); } ``` ## Arguments None. ## Response [SendEmailResult](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail-emailresult.md)[] ## Fault [`BCC_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`BCC_SELF_NOT_ALLOWED_IF_BCC_COMPLIANCE_ENABLED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`EMAIL_NOT_PROCESSED_DUE_TO_PRIOR_ERROR`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`ERROR_IN_MAILER`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_CONTENT_TYPE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_EMAIL_ADDRESS`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`INVALID_ID_FIELD`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`INVALID_MESSAGE_ID_REFERENCE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`MALFORMED_ID`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#exceptioncode) [`REQUIRED_FIELD_MISSING`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`SINGLE_EMAIL_LIMIT_EXCEEDED`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`TEMPLATE_NOT_ACTIVE`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) [`UNVERIFIED_SENDER_ADDRESS`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md#statuscode) <!-- document id=630e778b71826c7d2e7f1fbd6575eae74ca23f2cbc077dc55acc3860fa86e5fa url=/developer/current/en-us/platform/api/guides/api/utils/sforce-api-calls-sendemail-emailresult.md --> # SendEmailResult The [`sendEmail()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail.md) call returns a list of SendEmailResult objects. Each SendEmailResult object has the following properties: |Name|Type|Description| |----|----|-----------| |`success`|boolean|If sending single email: Indicates whether the email was successfully accepted for delivery by the message transfer agent (`true`) or not (`false`). Even if `success` = `true`, it does not mean the intended recipients received the email, as it could have bounced or been blocked by a spam blocker. Also, even if the email is successfully accepted for delivery by the message transfer agent, there can still be errors in the error array related to individual addresses within the email. If sending mass email: Indicates whether the email was successfully added to the queue for processing (`true`) or not (`false`). Even if the email was added to the queue, there can still be processing errors that prevent delivery to the intended recipients.| |`SendEmailError`|Error[]|If an error occurred during the [`sendEmail()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail.md) call, a list of `SendEmailError` objects is returned. For single email, errors indicate that Salesforce wasn't able to deliver the email. For mass email, errors indicate that the email wasn't added to the queue for processing.| ## SendEmailError SendEmailError can have the following attributes: |Name|Type|Description| |----|----|-----------| |`Fields`|Field[]|Reserved for future use. Array of one or more field names. Identifies which fields in the object, if any, affected the error condition.| |`Message`|string|Error message text.| |`StatusCode`|`statusCode`|A code that characterizes the error. The full list of status codes is available in [the WSDL file for your organization](https://developer.salesforce.com/docs/platform/api/quickstart/sforce-api-quickstart-intro.md).| |`TargetObjectId`|ID|The object ID of the target for which the error occurred.| **note:** If an error occurs that prevents [`sendEmail()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-sendemail.md) from sending the email to one or more targets, each `TargetObjectId` for those targets has an associated error in SendEmailResult. A `TargetObjectId` that does not have an associated error in SendEmailResult indicates the email was sent to the target. If SendEmailResult has an error that does not have an associated `TargetObjectId`, no email was sent. The following is an example of how to parse through a resulting set for errors: ```java Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); email.setToAddresses(new String[] { 'admin@acme.com' }); email.setSubject('my subject'); email.setPlainTextBody('plain text body'); List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[] { email }); if (!results.get(0).isSuccess()) { System.StatusCode statusCode = results.get(0).getErrors()[0].getStatusCode(); String errorMessage = results.get(0).getErrors()[0].getMessage(); } ``` <!-- document id=a4b19156a7a10263885be908fef33d40099abe6aa40d16de5d1103c43f127ccb url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/email-and-templates/pages-email-intro.md --> # Sending an Email with Visualforce It is possible to send email using Visualforce by creating a [custom controller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/controller/pages-controller-custom.md) to deliver the message. The Apex `Messaging.SingleEmailMessage` class handles the outbound email functionality available to Salesforce. The following topics demonstrate a number of features available when sending email through Visualforce: - [Creating a Custom Controller with the Messaging Class](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-email-custom-controller.md) - [Creating an Email Attachment](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-email-sending-attachments.md) <!-- document id=b6caec298436d7f0fbf7aca96f23bb262bc8c72a95e4113f6b6716b3b6b2a922 url=/developer/current/en-us/platform/change-data-capture/guides/change-data-capture/cdc-data-diff.md --> # Sending Data Differences for Fields of Updated Records To reduce the event payload size and improve performance, Salesforce sometimes sends data differences of updated text values. For large text fields, such as Description or Long Text Area fields that contain at least 1,000 characters, only the data differences might be sent. Data differences use the unified diff format. Differences are computed for each line in the text value. The diff algorithm breaks the field value into lines by using the line breaks found in the value. If sending the diff for updates of large text fields does not reduce the field size, the entire value is sent. The diff value is **not** sent for the following conditions. - The length of the field value is less than 1,000 characters. - The difference between the old and new values is greater than 50% in length. - More than 25% of the lines of the total of number of lines in the old and new values are changed. - The diff’s length is greater than the length of the new value. For more information about the unified diff format and the diff utility, see the [Diff Utility](https://en.wikipedia.org/wiki/Diff_utility#Unified_format) Wikipedia article. The diff value includes an SHA-256 hash value that is computed on the entire updated value. Use the hash value to verify that the reconstructed value matches the original value before it was converted to a diff. To do so, compute the SHA-256 hash after expanding the diff value. Then compare the two hash values to ensure that they’re equal. If the reconstructed content is different from the original content, the hash value is different. To compute an SHA-256 hash value, you can use a utility such as the UNIX sha256sum command or the [DigestUtils class](https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html) from the Apache Commons library. - **[Data Differences in Event Fields](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-data-diff-event-fields.md)** When the updated text field value is sent as a diff, it contains the SHA-256 hash value and data differences in the unified diff format. - **[How to Reconstruct a Field from Its Diff Value](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-data-diff-event-fields-reconstruct.md)** The value of a diff field is in the unified diff format. Use a diff utility to obtain the full field value from the diff. - **[Considerations for Newline Characters and Computing the SHA-256 Hash](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-data-diff-event-fields-considerations.md)** The content that Salesforce uses to generate the SHA-256 hash might have newline characters transformed by the browser. Many browsers transform newline characters to `\r\n` in record field values before records are stored in Salesforce. Also, Salesforce trims leading and trailing white spaces in field values. <!-- document id=b6fefd26a631162fa4506e562b37862e3202e633a4db5ce5a7b01514bc68f195 url=/developer/current/en-us/platform/aura-platform/guides/aura/container/container-sending-messages.md --> # Sending Messages from the Lightning Container Component Use the `onmessage` attribute of `lightning:container` to specify a method for handling messages to and from the contents of the component—that is, the embedded app. The contents of `lightning:container` are wrapped within an iframe, and this method allows you to communicate across the frame boundary. This example shows an Aura component that includes `lightning:container` and has three attributes, `messageToSend`, `messageReceived`, and `error`. This example uses the same code as the one in [Using a Third-Party Framework](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-js.md#using-a-third-party-framework). ```html <aura:component access="global" implements="flexipage:availableForAllPageTypes" > <aura:attribute access="private" name="messageToSend" type="String" default=""/> <aura:attribute access="private" name="messageReceived" type="String" default=""/> <aura:attribute access="private" name="error" type="String" default=""/> <div> <lightning:input name="messageToSend" value="{!v.messageToSend}" label="Message to send to React app: "/> <lightning:button label="Send" onclick="{!c.sendMessage}"/> <br/> <lightning:textarea value="{!v.messageReceived}" label="Message received from React app: "/> <br/> <aura:if isTrue="{! !empty(v.error)}"> <lightning:textarea name="errorTextArea" value="{!v.error}" label="Error: "/> </aura:if> <lightning:container aura:id="ReactApp" src="{!$Resource.SendReceiveMessages + '/index.html'}" onmessage="{!c.handleMessage}" onerror="{!c.handleError}"/> </div> </aura:component> ``` `messageToSend` represents a message sent from Salesforce to the framed app, while `messageReceived` represents a message sent by the app to the Aura component. `lightning:container` includes the required `src` attribute, an `aura:id`, and the `onmessage` attribute. The `onmessage` attribute specifies the message-handling method in your JavaScript controller, and the `aura:id` allows that method to reference the component. This example shows the component’s JavaScript controller. ```javascript ({ sendMessage : function(component, event, helper) { var msg = { name: "General", value: component.get("v.messageToSend") }; component.find("ReactApp").message(msg); }, handleMessage: function(component, message, helper) { var payload = message.getParams().payload; var name = payload.name; if (name === "General") { var value = payload.value; component.set("v.messageReceived", value); } else if (name === "Foo") { // A different response } }, handleError: function(component, error, helper) { var e = error; } }) ``` This code does a couple of different things. The `sendMessage` action sends a message from the enclosing Aura component to the embedded app. It creates a variable, `msg`, that has a JSON definition including a `name` and a `value`. This definition of the message is user-defined—the message’s payload can be a value, a structured JSON response, or something else. The `messageToSend` attribute of the Aura component populates the `value` of the message. The method then uses the component’s `aura:id` and the `message()` function to send the message back to the Aura component. The `handleMessage` method receives a message from the embedded app and handles it appropriately. It takes a component, a message, and a helper as arguments. The method uses conditional logic to parse the message. If this is the message with the `name` and `value` we’re expecting, the method sets the Aura component’s `messageReceived` attribute to the `value` of the message. Although this code only defines one message, the conditional statement allows you to handle different types of message, which are defined in the `sendMessage` method. The handler code for sending and receiving messages can be complicated. It helps to understand the flow of a message between the Aura component, its controller, and the app. The process begins when user enters a message as the `messageToSend` attribute. When the user clicks **Send**, the component calls `sendMessage`. `sendMessage` defines the message payload and uses the `message()` method to send it to the app. Within the static resource that defines the app, the specified message handler function receives the message. Specify the message handling function within your JavaScript code using the lightning-container module’s `addMessageHandler()` method. See the [lightning:container NPM Module Reference](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-api-reference.md) for more information. When `lightning:container` receives a message from the framed app, it calls the component controller’s `handleMessage` method, as set in the `onmessage` attribute of `lightning:container`. The `handleMessage` method takes the message, and sets its value as the `messageReceived` attribute. Finally, the component displays `messageReceived` in a `lightning:textarea`. This is a simple example of message handling across the container. Because you implement the controller-side code and the functionality of the app, you can use this functionality for any kind of communication between Salesforce and the app embedded in `lightning:container`. **important:** Don't send cryptographic secrets like an API key in a message. It's important to keep your API key secure. **See Also** - [Lightning Container](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-overview.md) - [Using a Third-Party Framework](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-js.md) - [Handling Errors in Your Container](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-handling-errors.md) <!-- document id=c03a57a56e0ca09d488449b191137f6a07bf9fcbfbc0fc4ce297a85b3fa548ec url=/developer/current/en-us/platform/aura-platform/guides/aura/container/container-messages-npm.md --> # Sending Messages to the Lightning Container Component Use the methods in the lightning-container NPM module to send messages from the JavaScript code framed by `lightning:container`. The Lightning-container NPM module provides methods to send and receive messages between your JavaScript app and the Lightning container component. You can see the lightning-container module on the NPM [website](https://www.npmjs.com/package/lightning-container). Add the lightning-container module as a dependency in your code to implement the messaging framework in your app. ```javascript import LCC from 'lightning-container'; ``` `lightning-container` must also be listed as a dependency in your app’s package.json file. The code to send a message to `lightning:container` from the app is simple. This code corresponds to the code samples in [Sending Messages from the Lightning Container Component](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-sending-messages.md#sending-messages-from-the-lightning-container-component) and [Handling Errors in Your Container](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-handling-errors.md#handling-errors-in-your-container). ```javascript sendMessage() { LCC.sendMessage({name: "General", value: this.state.messageToSend}); } ``` This code, part of the static resource, sends a message as an object containing a name and a value, which is user-defined. When the app receives a message, it’s handled by the function mounted by the `addMessageHandler()` method. In a React app, functions must be mounted to be part of the document-object model and rendered in the output. The lightning-container module provides similar methods for defining a function to handle errors in the messaging framework. For more information, see [lightning:container NPM Module Reference](https://developer.salesforce.com/docs/platform/aura-platform/guide/container-api-reference.md#lightningcontainer-npm-module-reference) **important:** Don't send cryptographic secrets like an API key in a message. It's important to keep your API key secure. <!-- document id=89918e8c2eeb300237484402c8a67d3322cc7908763210e5c7b7f0212cff3d98 url=/developer/current/en-us/platform/mobile-push-notifications/guides/mobile-push-notifications/pns-sending-notifications.md --> # Sending Mobile Notifications To send mobile notifications, Salesforce offers several options: Apex, REST API, and, in some cases, declarative feature-based tools. The type of notification, the delivery channel, and your skill comfort levels guide your choice. Send Apex push notifications with the `Messaging.PushNotification` methods in Apex triggers, or through the `PushNotifications` API. You can send custom notifications through the `customNotificationAction` API, [Process Builder](https://help.salesforce.com/articleView?id=notif_builder_custom_process.htm), or [Flow](https://help.salesforce.com/articleView?id=flow_ref_elements_actions_sendcustomnotification.htm). ## See Also - [Send Mobile Push Notifications](https://help.salesforce.com/articleView?id=connected_app_mobile_push_notifications.htm) - [Considerations for Notification Builder](https://help.salesforce.com/articleView?id=notif_builder_considerations.htm) - [Send Custom Notifications with Notification Builder Platform](https://help.salesforce.com/articleView?id=connected_app_notifications_custom.htm) - [Other Ways to Send a Custom Notification](https://help.salesforce.com/articleView?id=notif_builder_custom_other.htm) - **[Using Apex Triggers to Send Push Notifications](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-apex-trigger.md)** An Apex trigger creates new notifications and sends them to a specified external client app. - **[Custom Notification Actions](https://developer.salesforce.com/docs/api-action/guides/api-action/objects/actions-obj-custom-notification.md)** Send custom notifications to recipients via desktop or mobile channels. <!-- document id=86a23f9797e9843892a8ba3baa62e5eb1a8ee6a27cf66bf72146cc2a6c702f0d url=/developer/current/en-us/platform/aura-platform/guides/aura/container/container-npm-sendmessage.md --> # sendMessage() Sends a message from the framed JavaScript code to the Aura component. ## Sample Used within a JavaScript app uploaded as a static resource and referenced by `lightning:container`, this example sends a message from the app to `lightning:container`. ```javascript sendMessage() { LCC.sendMessage({name: "General", value: this.state.messageToSend}); } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`userMsg`|any|While the data sent in the message is entirely under your control, by convention it’s an object with name and value fields.| ## Response None. <!-- document id=9b6045a0a8b416e85bcaa0959e7a6660dc34a7570319c52649f17d62b1cf43b6 url=/developer/current/en-us/platform/platform-events/guides/platform-events/objects/sforce-api-objects-serviceappointmentevent.md --> # ServiceAppointmentEvent Notifies subscribers of the service appointment details that are generated from the event platform. This object is available in API version 59.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows| | |Processes| | |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/ServiceAppointmentEvent` ## Special Access Rules This object is available when Salesforce Scheduler is enabled. ## Fields ### `AsgnRsrcApptSchdDtlEvent` **Type:** [AsgnRsrcApptSchdEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-asgnrsrcapptschdevent.md)[] **Properties:** Nillable **Description:** One or multiple assigned resource records related to the scheduler appointment event. ### `ChangeType` **Type:** string **Properties:** Nillable **Description:** The operation that caused the change. For example: CREATE, UPDATE, DELETE. ### `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. ### `ServiceApptSchduleEvent` **Type:** [SvcApptSchdEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-svcapptschdevent.md)[] **Properties:** Nillable **Description:** The service appointment related to the scheduler appointment event. <!-- document id=e0deff120208be7c1d123e4d7559c0b7036a7b6461829475f460ae3f83b5dd22 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-activate-session-permission-set.md --> # Session-Based Permission Set Actions Activate or deactivate a session-based permission set for the current user's API session. This object is available in API version 40.0 and later. This action activates or deactivates the provided permission set for the current user's API session. The activation or deactivation doesn't affect other sessions. The permission set must already be assigned to the current user. ## Supported REST HTTP Methods **URIs:** - Activate session-based permission set: `/services/data/vXX.X/actions/standard/activateSessionPermSet` - Deactivate session-based permission set: `/services/data/vXX.X/actions/standard/deactivateSessionPermSet` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`PermSetName`|string|Required. Specifies the developer name of the permission set.| |`PermSetNamespace`|string|Optional. Specifies the namespace of the permission set.| ## Outputs None. <!-- document id=25aa66a9622587690ed51974799ad9be8e067b9b5186262c477a7eb6ad177e5f url=/developer/current/en-us/platform/api/guides/api/header/sforce-api-header-sessionheader.md --> # SessionHeader Specifies the session ID returned from the login server after a successful `login()`. This session ID is used in all subsequent calls. In version 12.0 and later, include the API namespace in the SOAP message associated with this header. The namespace is defined in the enterprise or partner WSDL. ## API Calls All calls, including utility calls. ## Fields ### `sessionId` **Type:** string **Description:** Session ID returned by the `login()` call to be used for subsequent call authentication. ## Sample Code See the examples provided for [`login()`](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_login.htm). <!-- document id=10580bbb4bcf5c39f29c918885d77922914fd295d8220e82e385d899e44b4d7b url=/developer/current/en-us/platform/platform-events/guides/platform-events/objects/sforce-api-objects-sessionhijackingevent.md --> # SessionHijackingEvent Tracks when unauthorized users gain ownership of a Salesforce user’s session with a stolen session identifier. To detect such an event, Salesforce evaluates how significantly a user’s current browser fingerprint diverges from the previously known fingerprint using a probabilistically inferred significance of change. This object is available in API version 49.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers| | |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes| | |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/SessionHijackingEvent` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. **note:** The Machine Learning (ML) models that power Threat Detection analyze data to ensure accurate identification, which requires a brief processing time. This results in an expected time difference between the Event Detection Date and the Event Creation Date. ## Event Delivery Allocation Enforced No ## Fields ### `CurrentIp` **Type:** string **Properties:** Nillable **Description:** The IP address of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousIp` field for the previous IP address. If the IP address didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousIp` field value. For example, `126.7.4.2`. ### `CurrentPlatform` **Type:** string **Properties:** Nillable **Description:** The platform of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousPlatform` field for the previous platform. If the platform didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousPlatform` field value. For example, `MacIntel` or `Win32`. ### `CurrentScreen` **Type:** string **Properties:** Nillable **Description:** The screen of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousScreen` field for the previous screen. If the screen didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousScreen` field value. For example, `(900.0,1440.0)` or `(720,1280)`. ### `CurrentUserAgent` **Type:** textarea **Properties:** Nillable **Description:** The user agent of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousUserAgent` field for the previous user agent. If the user agent didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousUserAgent` field value. For example, `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36`. ### `CurrentWindow` **Type:** string **Properties:** Nillable **Description:** The browser window of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousWindow` field for the previous window. If the window didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousWindow` field value. For example, `(1200.0,1920.0)`. ### `EvaluationTime` **Type:** double **Properties:** Nillable **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Nillable **Description:** The time when the anomaly was detected. For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Nillable **Description:** The unique ID of the event, which is shared with the corresponding storage object. For example, `0a4779b0-0da1-4619-a373-0a36991dff90`. Use this field to correlate the event with its storage object. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later. ### `LoginKey` **Type:** string **Properties:** Nillable **Description:** The string that ties together all events in a given user's login session. The session starts with a login event and ends with either a logout event or the user session expiring. For example, lUqjLPQTWRdvRG4. ### `PolicyId` **Type:** reference **Properties:** Nillable **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. A relationship field. **Relationship Name:** Policy **Relationship Type:** Lookup **Refers To:** TransactionSecurityPolicy ### `PolicyOutcome` **Type:** picklist **Properties:** Nillable, Restricted picklist **Description:** The result of the transaction policy. Possible values are: - `Error` - The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user isn't blocked from performing the operation. - `NoAction` - The policy didn't trigger. - `Notified` - A notification was sent to the recipient. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `PreviousIp` **Type:** string **Properties:** Nillable **Description:** The IP address of the previous fingerprint. The IP address of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentIp` field for the newly observed IP address. For example, `128.7.5.2`. ### `PreviousPlatform` **Type:** string **Properties:** Nillable **Description:** The platform of the previous fingerprint. The platform of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentPlatform` field for the newly observed platform. For example, `Win32` or `iPhone`. ### `PreviousScreen` **Type:** string **Properties:** Nillable **Description:** The screen of the previous fingerprint. The screen of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentScreen` field for the newly observed screen. For example, (`1200.0,1920.0)`. ### `PreviousUserAgent` **Type:** textarea **Properties:** Nillable **Description:** The user agent of the previous fingerprint. The user agent of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentUserAgent` field for the newly observed user agent. For example, `Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)`. ### `PreviousWindow` **Type:** string **Properties:** Nillable **Description:** The browser window of the previous fingerprint. The window of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentWindow` field for the newly observed window. For example, `(1600.0,1920.0)`. ### `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. ### `Score` **Type:** double **Properties:** Nillable **Description:** Specifies how significant the new browser fingerprint deviates from the previous one. The score is a number from 0.0 (lowest amount of deviation) through 1.0 (highest amount of deviation). The event exposes five field pairs (such as `CurrentIp` and `PreviousIp`) to view the before and after data for the five most interesting browser features that contributed to this anomaly. See the `SecurityEventData` field for all contributing features in JSON format. Salesforce detects session hijacking by comparing browser fingerprints in a given user session and evaluating how significantly a newly observed fingerprint deviates from the existing one. A large deviation score (0.8 or more) between two intra-session fingerprints indicates that two different browsers are active in the same session. The presence of two active browsers usually means that session hijacking has occurred. ### `SecurityEventData` **Type:** string **Properties:** Nillable **Description:** The set of browser fingerprint features about the session hijacking that triggered this event. See the [Threat Detection documentation](https://help.salesforce.com/articleView?id=real_time_em_threat_session.htm&type=5) for the list of possible features. For example, let’s say that a user’s current browser fingerprint diverges from their previously known fingerprint. If Salesforce concludes their session was hijacked, it fires this event and the contributing features are captured in this field in JSON format. Each feature describes a particular browser fingerprint property, such as the browser user agent, window, or platform. The data includes the current and previous values for each feature. **Example:** ```nolang [ { "featureName": "userAgent", "featureContribution": "0.45 %", "previousValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142", "currentValue": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36." }, { "featureName": "ipAddress", "featureContribution": "0.23 %", "previousValue": "201.17.237.77", "currentValue": "182.64.210.144" }, { "featureName": "platform", "featureContribution": "0.23 %", "previousValue": "Win32", "currentValue": "MacIntel" }, { "featureName": "screen", "featureContribution": "0.23 %", "previousValue":"(1050.0,1680.0)", "currentValue": "(864.0,1536.0)" }, { "featureName": "window", "featureContribution": "0.17 %", "previousValue": "1363x1717", "currentValue": "800x1200" } ] ``` ### `SessionKey` **Type:** string **Properties:** Nillable **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. For example, vMASKIU6AxEr+Op5. ### `SourceIp` **Type:** string **Properties:** Nillable **Description:** The source IP address of the client that logged in. For example, `126.7.4.2`. ### `Summary` **Type:** textarea **Properties:** Nillable **Description:** A text summary of the threat that caused this event to be created. The summary lists the browser fingerprint features that most contributed to the threat detection along with their contribution to the total score. - `Changes to (userAgent, platform, ipAddress) were not expected based on this user's profile. These top 3 deviations contributed (1, 1, 0.922) to the total score, respectively` - `Changes to (ipAddress, userAgent, platform, languages, color) were not expected based on this user's profile. These top 5 deviations contributed (1, 0.695, 0.695, 0.25, 0.223) to the total score, respectively` ### `UserId` **Type:** reference **Properties:** Nillable **Description:** The origin user’s unique ID. For example, `005000000000123`. A polymorphic relationship field. **Relationship Name:** User **Relationship Type:** Lookup **Refers To:** User ### `Username` **Type:** string **Properties:** Nillable **Description:** The origin username in the format of `user@company.com` at the time the event was created. <!-- document id=6983a5e503bdbf93fbc5ae94748e9d70260bbafe56901df0db1ff0369ff3766f url=/developer/current/en-us/platform/platform-events/guides/platform-events/objects/sforce-api-objects-sessionhijackingeventstore.md --> # SessionHijackingEventStore Tracks when unauthorized users gain ownership of a Salesforce user’s session with a stolen session identifier. To detect such an event, Salesforce evaluates how significantly a user’s current browser fingerprint diverges from the previously known fingerprint using a probabilistically inferred significance of change. SessionHijackingEventStore is an object that stores the event data of SessionHijackingEvent. This object is available in API version 49.0 and later. ## Supported Calls `describeLayout()`, `describeSObjects()`, `getDeleted()`, `getUpdated()`, `query()` ## Special Access Rules Accessing this object requires either the Salesforce Shield or Event Monitoring add-on subscription and the View Real-Time Event Monitoring Data user permission. **note:** The Machine Learning (ML) models that power Threat Detection analyze data to ensure accurate identification, which requires a brief processing time. This results in an expected time difference between the Event Detection Date and the Event Creation Date. ## Fields ### `CurrentIp` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The IP address of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousIp` field for the previous IP address. If the IP address didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousIp`field value. For example, `126.7.4.2.` ### `CurrentPlatform` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The platform of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousPlatform` field for the previous platform. If the platform didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousPlatform` field value. For example, `MacIntel` or `Win32`. ### `CurrentScreen` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The screen of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousScreen` field for the previous screen. If the screen didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousScreen` field value. For example, (`900.0,1440.0)` or `(720,1280)`. ### `CurrentUserAgent` **Type:** textarea **Properties:** Nillable **Description:** The user agent of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousUserAgent` field for the previous user agent. If the user agent didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousUserAgent` field value. For example, `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36`. ### `CurrentWindow` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The browser window of the newly observed fingerprint that deviates from the previous fingerprint. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `PreviousWindow` field for the previous window. If the window didn’t contribute to the observed fingerprint deviation, the value of this field is the same as the `PreviousWindow` field value. For example, `(1200.0,1920.0)`. ### `EvaluationTime` **Type:** double **Properties:** Filter, Nillable, Sort **Description:** The amount of time it took to evaluate the policy in milliseconds. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `EventDate` **Type:** dateTime **Properties:** Filter, Sort **Description:** Required. The time when the anomaly was detected. For example, `2020-01-20T19:12:26.965Z`. Milliseconds are the most granular setting. ### `EventIdentifier` **Type:** string **Properties:** Filter, Group, Sort **Description:** Required. The unique ID of the event. For example, `0a4779b0-0da1-4619-a373-0a36991dff90`. ### `LastReferencedDate` **Type:** dateTime **Properties:** Filter, Nillable, Sort **Description:** The timestamp for when the current user last viewed a record related to this record. ### `LastViewedDate` **Type:** dateTime **Properties:** Filter, Nillable, Sort **Description:** The timestamp for when the current user last viewed this record. If this value is null, it’s possible that this record was referenced (`LastReferencedDate`) and not viewed. ### `LoginKey` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The string that ties together all events in a given user’s login session. The session starts with a login event and ends with either a logout event or the user session expiring. For example, lUqjLPQTWRdvRG4. ### `PolicyId` **Type:** reference **Properties:** Filter, Group, Nillable, Sort **Description:** The ID of the transaction policy associated with this event. For example, 0NIB000000000KOOAY. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `PolicyOutcome` **Type:** picklist **Properties:** Filter, Group, Nillable, Restricted picklist, Sort **Description:** The result of the transaction policy. Possible values are: - `Error` - The policy caused an undefined error when it executed. - `ExemptNoAction`—The user is exempt from transaction security policies, so the policy didn’t trigger. - `MeteringBlock`—The policy took longer than 3 seconds to process, so the user was blocked from performing the operation. - `MeteringNoAction`—The policy took longer than 3 seconds to process, but the user isn't blocked from performing the operation. - `NoAction` - The policy didn't trigger. - `Notified` - A notification was sent to the recipient. This field isn’t populated until all transaction security policies are processed for the real-time event. ### `PreviousIp` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The IP address of the previous fingerprint. The IP address of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentIp` field for the newly observed IP address. For example, `128.7.5.2`. ### `PreviousPlatform` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The platform of the previous fingerprint. The platform of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentPlatform` field for the newly observed platform. For example, `Win32` or `iPhone`. ### `PreviousScreen` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The screen of the previous fingerprint. The screen of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentScreen` field for the newly observed screen. For example, `(1200.0,1920.0)`. ### `PreviousUserAgent` **Type:** textarea **Properties:** Nillable **Description:** The user agent of the previous fingerprint. The user agent of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentUserAgent` field for the newly observed user agent. For example, `Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)`. ### `PreviousWindow` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The browser window of the previous fingerprint. The window of the newly observed fingerprint deviates from this value. The difference between the current and previous values is one indicator that a session hijacking attack has occurred. See the `CurrentWindow` field for the newly observed window. For example, `(1600.0,1920.0)`. ### `Score` **Type:** double **Properties:** Filter, Nillable, Sort **Description:** Specifies how significant the new browser fingerprint deviates from the previous one. The score is a number from 0.0 (lowest amount of deviation) through 1.0 (highest amount of deviation). The event exposes five field pairs (such as `CurrentIp` and `PreviousIp`) to view the before and after data for the five most interesting browser features that contributed to this anomaly. See the `SecurityEventData` field for all contributing features in JSON format. Salesforce detects session hijacking by comparing browser fingerprints in a given user session and evaluating how significantly a newly observed fingerprint deviates from the existing one. A large deviation score (0.8 or more) between two intra-session fingerprints indicates that two different browsers are active in the same session. The presence of two active browsers usually means that session hijacking has occurred. ### `SecurityEventData` **Type:** textarea **Properties:** Nillable **Description:** The set of browser fingerprint features about the session hijacking that triggered this event. See the [Threat Detection documentation](https://help.salesforce.com/articleView?id=real_time_em_threat_session.htm&type=5) for the list of possible features. For example, let’s say that a user’s current browser fingerprint diverges from their previously known fingerprint. If Salesforce concludes their session was hijacked, it fires this event and the contributing features are captured in this field in JSON format. Each feature describes a particular browser fingerprint property, such as the browser user agent, window, or platform. The data includes the current and previous values for each feature. **Example:** ```nolang [ { "featureName": "userAgent", "featureContribution": "0.45 %", "previousValue": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142", "currentValue": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36." }, { "featureName": "ipAddress", "featureContribution": "0.23 %", "previousValue": "201.17.237.77", "currentValue": "182.64.210.144" }, { "featureName": "platform", "featureContribution": "0.23 %", "previousValue": "Win32", "currentValue": "MacIntel" }, { "featureName": "screen", "featureContribution": "0.23 %", "previousValue":"(1050.0,1680.0)", "currentValue": "(864.0,1536.0)" }, { "featureName": "window", "featureContribution": "0.17 %", "previousValue": "1363x1717", "currentValue": "800x1200" } ] ``` ### `SessionHijackingEventNumber` **Type:** string **Properties:** Autonumber, Defaulted on create, Filter, idLookup, Sort **Description:** The unique number assigned by the system after the event is received in Salesforce. This ID is different than the replayID field on the streaming event SessionHijackingEvent. You can't change the format or value for this field. ### `SessionKey` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The user’s unique session ID. Use this value to identify all user events within a session. When a user logs out and logs in again, a new session is started. For example, vMASKIU6AxEr+Op5. ### `SourceIp` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The source IP address of the client that logged in. For example, `126.7.4.2`. ### `Summary` **Type:** textarea **Properties:** Nillable **Description:** A text summary of the threat that caused this event to be created. The summary lists the browser fingerprint features that most contributed to the threat detection along with their contribution to the total score. - `Changes to (userAgent, platform, ipAddress) were not expected based on this user's profile. These top 3 deviations contributed (1, 1, 0.922) to the total score, respectively` - `Changes to (ipAddress, userAgent, platform, languages, color) were not expected based on this user's profile. These top 5 deviations contributed (1, 0.695, 0.695, 0.25, 0.223) to the total score, respectively` ### `UserId` **Type:** reference **Properties:** Filter, Group, Nillable, Sort **Description:** The origin user’s unique ID. For example, `005000000000123`. ### `Username` **Type:** string **Properties:** Filter, Group, Nillable, Sort **Description:** The origin username in the format of `user@company.com` at the time the event was created. ## Associated Object This object has the following associated object. It’s available in the same API version as this object. [SessionHijackingEventStoreFeed](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_associated_objects_feed.htm): Feed tracking is available for the object. <!-- document id=b4e84d4800b5315f35ddb36c5a30fdda1858c35f35d9075ba91ec33de166a8b5 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-salesforce1-set-location.md --> # Set Canvas App Location and Add it to the Navigation Menu To add a canvas app to appear in the Salesforce mobile app navigation menu, you must set the location and add it to the mobile navigation. 1. In Salesforce, from Setup, enter `Apps` in the `Quick Find` box, then select **Apps**. 2. In the Connected Apps related list, click the app you want to make available in the navigation pane and click **Edit**. 3. In the Canvas App Settings section, select **Canvas**. 4. In the `Locations` field, select **Mobile Nav** and click **Add**. 5. Click **Save**. 6. For the canvas app to appear in the navigation menu you must add it to the mobile navigation. From Setup, enter `Navigation` in the `Quick Find` box, then select **Salesforce Navigation**. 7. From the available menu items, select your app and click **Add**. 8. Click **Save**. <!-- document id=f2e5d3da5a34bcd40843259a1b01d3abb054c9f555713f6e5f81a799c90e9b52 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/chatter/canvas-apps-publisher-set-location.md --> # Set Canvas App Location and Create the Action To add a canvas app to the publisher or action bar, you must set the location and create the action when you create the canvas app. 1. In Salesforce, from Setup, enter `Apps` in the `Quick Find` box, then select **App Manager**. 2. In the Connected Apps related list, click **New**. Fill out the basic fields for your canvas app. See [Use a Connected App](https://developer.salesforce.com/docs/platform/quick-start/quick-start-create-canvas-app.md). 3. In the Canvas App settings, select **Canvas** and in the `Locations` field, select Publisher. You must select this location for your canvas app to appear in both the publisher in the full Salesforce site and in the action bar in the Salesforce mobile app. 4. Select the `Create Actions Automatically` field. This creates a quick action for the canvas app. 5. To hide the publisher header, which contains the "What are you working on?" text, select `Hide Publisher Header`. This hides the header in both the full Salesforce site and in the Salesforce mobile app. 6. To hide the publisher **Share** button from users in both the full Salesforce site and in the Salesforce mobile app, select `Hide Publisher Share Button`. This checkbox is enabled only if `Hide Publisher Header` is selected. For the canvas app to appear as an action, you must add the action to the global publisher layout. See “Customizing Global Publisher Layouts” in the Salesforce Help. **See Also** - [Where Canvas Apps Appear](https://developer.salesforce.com/docs/platform/introducing/canvas-apps-where-they-appear.md) - [Create the Action Manually](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-publisher-create-action.md) - [Canvas Apps in the Publisher](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-apps-in-publisher.md) <!-- document id=125aa3810cf78180ca8b508b9d531f381c5a1f7b8b66d0162d50d99019a67a90 url=/developer/current/en-us/platform/aura-platform/guides/aura/components/components-using-flow-inputs-set.md --> # Set Flow Input Variable Values from a Wrapper Aura Component When you embed a flow in a custom Aura component, give the flow more context by initializing its variables. In the component's controller, create a list of maps, then pass that list to the startFlow method. **tip:** We recommend using Lightning web components because they perform better and provide the latest functionality. See [Embed a Flow in a Custom Lightning Web Component](https://developer.salesforce.com/docs/platform/lwc/guide/use-flow-embed-component.html). You can set variables only at the beginning of an interview, and the variables you set must allow input access. If you reference a variable that doesn’t allow input access, attempts to set the variable are ignored. For each variable you set, provide the variable's `name`, `type`, and `value`. For type, use the API name for the flow data type. For example, for a record variable use SObject, and for a text variable use String. ```javascript { name : "varName", type : "flowDataType", value : valueToSet }, { name : "varName", type : "flowDataType", value : [ value1, value2] }, ... ``` ## Example: Set Values for Variables In this example, this JavaScript controller sets values for a number variable, a date collection variable, and a couple of record variables. The Record data type in Flow Builder corresponds to SObject here. ```javascript ({ init: function (component) { // Find the component whose aura:id is "flowData" var flow = component.find("flowData"); var inputVariables = [ { name: "numVar", type: "Number", value: 30 }, { name: "dateColl", type: "String", value: ["2016-10-27", "2017-08-01"] }, // Sets values for fields in the account record (sObject) variable. Id uses // the value of the component's accountId attribute. Rating uses a string. { name: "account", type: "SObject", value: { Id: component.get("v.accountId"), Rating: "Warm", }, }, // Set the contact record (sObject) variable to the value of the // component's contact attribute. We're assuming the attribute contains // the entire sObject for a contact record. { name: "contact", type: "SObject", value: component.get("v.contact") }, ]; flow.startFlow("myFlow", inputVariables); }, }); ``` ## Example: Retrieve the Most Recently Modified Account via an Apex Controller In this example, the Apex controller passes the data to the flow's record variable through the JavaScript controller. ```nolang <aura:component controller="AccountController" > <aura:attribute name="account" type="Account" /> <aura:handler name="init" value="{!this}" action="{!c.init}"/> <lightning:flow aura:id="flowData"/> </aura:component> ``` ```apex public with sharing class AccountController { @AuraEnabled public static Account getAccount() { return [SELECT Id, Name, LastModifiedDate FROM Account ORDER BY LastModifiedDate DESC LIMIT 1]; } } ``` ```javascript ({ init: function (component) { // Create action to find an account var action = component.get("c.getAccount"); // Add callback behavior for when response is received action.setCallback(this, function (response) { var state = response.getState(); if (state === "SUCCESS") { // Pass the account data into the component's account attribute component.set("v.account", response.getReturnValue()); // Find the component whose aura:id is "flowData" var flow = component.find("flowData"); // Set the account record (sObject) variable to the value of // the component's account attribute. var inputVariables = [ { name: "account", type: "SObject", value: component.get("v.account"), }, ]; // In the component whose aura:id is flowData, start your flow // and initialize the account record (sObject) variable. // Reference the flow's API name. flow.startFlow("myFlow", inputVariables); } else { console.log("Failed to get account date."); } }); // Send action to be executed $A.enqueueAction(action); }, }); ``` **See Also** - [_Component Library_: lightning:flow Component](https://developer.salesforce.com/docs/component-library/bundle/lightning:flow/documentation) - [Which Custom Lightning Component Attribute Types Are Supported in Flows?](https://developer.salesforce.com/docs/platform/aura-platform/guide/components-config-for-flow-tips-map.md) <!-- document id=7ba391a387892fc61dde5444098088991f134273626d0de10d10dc4cac80032b url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/flows/pages-flows-setting-values.md --> # Set Flow Variable Values from a Visualforce Page After you embed your flow in a Visualforce page, set the initial values of variables, record variables, collection variables, and record collection variables through the `<apex:param>` component. **note:** You can set variables only at the beginning of an interview. The `<apex:param>` tags are evaluated only once, when the flow is launched. You can set only variables that allow input access. If you reference a variable that doesn’t allow input access, attempts to set the variable are ignored. Compilation can fail for the Visualforce page, its `<apex:page>` component, or the Apex class. The following table lists the ways you can set a flow’s variable, record variable, and record collection variable values using Visualforce. |Method|Variables|Record Variables|Collection Variables|Record Collection Variables| |------|---------|----------------|--------------------|---------------------------| |Without a controller|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)| | | | |With a standard controller|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)| | | |With a standard List controller| | | |![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)| |With a custom Apex controller|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)| |With an Interview Map|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)|![checkmark](https://developer.salesforce.com/media/salesforce-pages-developers-guide/checkmark_16x16.png)| ## Setting Variable Values without a Controller This example sets `myVariable` to the value `01010101` when the interview starts. ```visualforce <apex:page> <flow:interview name="flowname"> <apex:param name="myVariable" value="01010101"/> </flow:interview> </apex:page> ``` ## Setting Variable Values with a Standard Controller You can use standard Visualforce controllers to set variables by passing in data from a record. This example sets the initial value of `myVariable` to the Visualforce expression `{!account}` when the interview starts. ```visualforce <apex:page standardController="Account" tabStyle="Account"> <flow:interview name="flowname"> <apex:param name="myVariable" value="{!account}"/> </flow:interview> </apex:page> ``` ## Setting a Record Collection Variable Value with a Standard List Controller Because record collection variables represent an array of values, you must use a standard list controller or a custom Apex controller. This example sets `myCollection` to the value of `{!accounts}` when the interview starts. ```visualforce <apex:page standardController="Account" tabStyle="Account" recordSetVar="accounts"> <flow:interview name="flowname"> <apex:param name="myCollection" value="{!accounts}"/> </flow:interview> </apex:page> ``` ## Setting Variable Values with a Custom Apex Controller For finer control over your Visualforce page than a standard controller allows, write a custom Apex controller that sets the variable value, and then reference that controller in your Visualforce page. This example uses Apex to set `myVariable` to a specific account’s Id when the interview starts. <!-- otherprops: controller --> ```apex_code public class MyCustomController { public Account apexVar {get; set;} public MyCustomController() { apexVar = [ SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1]; } } ``` ```visualforce <apex:page controller="MyCustomController"> <flow:interview name="flowname"> <apex:param name="myVariable" value="{!apexVar}"/> </flow:interview> </apex:page> ``` This example uses Apex to set a record collection variable `myAccount` to the `Id` and `Name` field values for every record with a `Name` of `Acme`. <!-- otherprops: controller --> ```apex_code public class MyCustomController { public Account[] myAccount { get { return [ SELECT Id, Name FROM account WHERE Name = 'Acme' ORDER BY Id ] ; } set { myAccount = value; } } public MyCustomController () { } } ``` ```visualforce <apex:page id="p" controller="MyCustomController"> <flow:interview id="i" name="flowname"> <apex:param name="accountColl" value="{!myAccount}"/> </flow:interview> </apex:page> ``` ## Setting Variable Values with an Interview Map This example uses an Interview map to set the value for `accVar` to a specific account’s Id when the interview starts. <!-- otherprops: controller --> ```apex_code public class MyCustomController { public Flow.Interview.TestFlow myflow { get; set; }  public MyCustomController() { Map<String, Object> myMap = new Map<String, Object>(); myMap.put('accVar', [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1]); myflow = new Flow.Interview.ModemTroubleShooting(myMap); } } ``` ```visualforce <apex:page controller="MyCustomController"> <flow:interview name="flowname" interview="{!myflow}"/> </apex:page> ``` Here’s a similar example that sets the value for `accVar` to a new account when the interview starts. <!-- otherprops: controller --> ```apex_code public class MyCustomController { public Flow.Interview.TestFlow myflow { get; set; }  public MyCustomController() { Map<String, List<Object>> myMap = new Map<String, List<Object>>(); myMap.put('accVar', new Account(name = 'Acme')); myflow = new Flow.Interview.ModemTroubleShooting(myMap); } } ``` ```visualforce <apex:page controller="MyCustomController"> <flow:interview name="flowname" interview="{!myflow}"/> </apex:page> ``` This example uses a map to add two values to a string collection variable (`stringCollVar`) and two values to a number collection variable (`numberCollVar`). <!-- otherprops: controller --> ```apex_code public class MyCustomController { public Flow.Interview.flowname MyInterview { get; set; } public MyCustomController() { String[] value1 = new String[]{'First', 'Second'}; Double[] value2 = new Double[]{999.123456789, 666.123456789}; Map<String, Object> myMap = new Map<String, Object>(); myMap.put('stringCollVar', value1); myMap.put('numberCollVar', value2); MyInterview = new Flow.Interview.flowname(myMap); } } ``` ```visualforce <apex:page controller="MyCustomController"> <flow:interview name="flowname" interview="{!MyInterview}" /> </apex:page> ``` <!-- document id=504560f07f39e5a9573a9cfd01bb8e53ab5844db74383e310e2cdf8b4f410a6c url=/developer/current/en-us/platform/salesforce-soql-sosl/guides/soql-sosl/sforce-api-calls-soql-select-set-options.md --> # SET OPTIONS Use the `SET OPTIONS` clause to configure query behavior. ## Syntax ```nolang [SET OPTIONS (optionName = optionValue [, optionName = optionValue])] ``` ## Example ```nolang SELECT Id, Name FROM MyDLO__dlm WHERE Status__c = 'Active' SET OPTIONS (dataspace = 'default', honorEmptyStrings = true) ``` ## `dataspace` Option Use `dataspace` to specify which dataspace to query when querying a DLO. If the `dataspace` isn’t specified, the query returns zero records. Valid only for DLO queries, not supported for data model object (DMO) queries. | Option | Values | | ----------- | ---------------------------- | | `dataspace` | `'<dataspaceName>'` (string) | **Example** ```nolang SELECT AccountId__c, Email__c FROM CustomerProfile__dlm SET OPTIONS (dataspace = 'default') ``` ## `honorEmptyStrings` Option Salesforce Platform objects don’t distinguish between `NULL` and an empty string (`''`). A SOQL query filtering on either value returns the same records. Data 360 DLOs treat `NULL` and empty string as different values. Use `honorEmptyStrings` to control how filtering behaves when querying DLOs. The `honorEmptyStrings` option also supports simple queries for DMOs. | Option | Values | Behavior | | ------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `honorEmptyStrings` | `true` | `NULL` and empty string are treated as different values. Filtering returns different record sets depending on whether the value is `NULL` or `''`. | | `honorEmptyStrings` | `false` (default) | `NULL` and empty string are treated as the same value. Consistent with querying Salesforce Platform objects. | **Examples** This query returns records where `EmailOptIn__c` is either `NULL` or `''`. ```nolang SELECT Id, EmailOptIn__c FROM ContactDLO__dlm WHERE EmailOptIn__c = '' SET OPTIONS (dataspace = 'default', honorEmptyStrings = false) ``` This query returns only records where `EmailOptIn__c` is an empty string. ```nolang SELECT Id, EmailOptIn__c FROM ContactDLO__dlm WHERE EmailOptIn__c = '' SET OPTIONS (dataspace = 'default', honorEmptyStrings = true) ``` ## `explicitNamespace` Option Use `explicitNamespace` to enable explicit namespace resolution for a dynamic SOQL query. This option is applicable to only managed Apex, and you must pass the option as a bind variable. See [Prevent Field Name Collisions in Managed SOQL Queries](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_manpkgs_dynamic_soql.htm) in the _Apex Developer Guide_. <!-- document id=a32a770525a972dc105a73b3730c72f472260c5689182e2cfc88e7546b9ce818 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-self-service-user-password-post.md --> # Set Self-Service User Password Sets a self-service user’s password based on the specified user ID. The password provided in the request body replaces the user’s existing password. This resource is available in REST API version 24.0 and later. You can only set one password per request. The new password must conform to the password policies for the organization, otherwise an INVALID_NEW_PASSWORD error is returned. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/SelfServiceUser/selfServiceUserId/password` **Formats:** JSON, XML **HTTP Method:** POST **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=a818be115a05967799929b5b6606bbf4fe8bb5e74e47fa8d7b5ae53706622a5e url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/quick-start-simple/quick-start-simple-set-app-location.md --> # Set the Canvas App Location for Connected Apps Specify where your canvas app can display to a user in Salesforce via a connected app. In Spring ’26, the creation of new connected apps is disabled by default. We recommend that you [use an external client app for your canvas integrations](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-set-app-location-eca.md) instead. To enable connected app creation in your org, contact Salesforce Customer Support. Before Spring ’26, when you create a canvas app via the Canvas App Previewer page, a connected app is created automatically. 1. From Setup, search for `Apps` in the `Quick Find` box, then select **App Manager** in Lightning Experience or **Connected Apps** in Classic. 2. In the related list, click the dropdown arrow for the app you just created and then click **Edit Settings.** 3. In the Canvas Apps Settings section, in the `Locations` field, select where the canvas app can appear to the user. For this walkthrough, select **Chatter Tab**. - **Chatter Feed**—The canvas app appears in the feed. If this option is selected, you must create a CanvasPost feed item and ensure that the current user has access to the canvas app. - **Chatter Tab**—The canvas app appears in the app navigation list on the Chatter tab. If this option is selected, the canvas app appears there automatically. - **Console**—The canvas app appears in the footer or sidebars of a Salesforce console. If this option is selected, you must choose where the canvas app appears in a console by adding it as a custom console component. - **Layouts and Mobile Cards**—The canvas app can appear on a page layout or a mobile card. If this option is selected, you choose where the canvas app appears by adding it to the page layout. - **Lightning Component**—The canvas app appears on your custom Lightning component [using the `force:canvasApp` component](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-aura-code-example.md). - **Mobile Nav**—The canvas app is accessible from the mobile app navigation menu. - **Open CTI**—The canvas app appears in the call control tool. If this option is selected, you must specify the canvas app in your call center’s definition file for it to appear. - **Publisher**—The canvas app appears in the Chatter publisher and action bar. If this option is selected, you must also create a canvas custom action and add it to the global publisher layout or to an object’s page layout. - **Visualforce Page**—The canvas app can appear on a Visualforce page . If you add an `<apex:canvasApp>` component to expose a canvas app on a Visualforce page, be sure to select this location for the canvas app; otherwise, you’ll receive an error. 4. Click **Save**. Because you selected **Chatter Tab**, your canvas app now appears in the left navigation pane on the Chatter tab in Salesforce Classic. **See Also** - [Quick Start](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-intro.md) - [Create the App](https://developer.salesforce.com/docs/platform/canvas-framework/guide/quick-start-simple-create-app.md) - [Where Canvas Apps Appear](https://developer.salesforce.com/docs/platform/canvas-framework/introducing/canvas-apps-where-they-appear.md) - [Quick Start—Advanced](https://developer.salesforce.com/docs/platform/canvas-framework/quick-start/quick-start-intro.md) <!-- document id=3a3b8fabda6bf39b3dd77fc8e4782d9f801b2800a9e7706edcb36fe0d0be5456 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/quick-start-simple/quick-start-simple-set-app-location-eca.md --> # Set the Canvas App Location for External Client Apps Specify where your canvas app can display to a user in Salesforce via an external client app. 1. In Lightning Experience, from Setup, search for `External Client App` in the `Quick Find` box, then select **External Client App Manager**. 2. In the related list, click the dropdown arrow for the app you just created and then click **Edit Settings.** 3. In the Canvas Apps Settings section, in the `Locations` field, select where the canvas app can appear to the user. For this example, select **Lightning Component**. - **Chatter Feed**—The canvas app appears in the feed. If this option is selected, you must create a CanvasPost feed item and ensure that the current user has access to the canvas app. - **Layouts and Mobile Cards**—The canvas app can appear on a page layout or a mobile card. If this option is selected, you choose where the canvas app appears by adding it to the page layout. - **Lightning Component**—The canvas app appears on your custom Lightning component [using the `force:canvasApp` component](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-aura-code-example.md). - **Mobile Nav**—The canvas app is accessible from the mobile app navigation menu. - **Publisher**—The canvas app appears in the Chatter publisher and action bar. If this option is selected, you must also create a canvas custom action and add it to the global publisher layout or to an object’s page layout. - **Visualforce Page**—The canvas app can appear on a Visualforce page . If you add an `<apex:canvasApp>` component to expose a canvas app on a Visualforce page, be sure to select this location for the canvas app; otherwise, you’ll receive an error. 4. Click **Save**. 5. Embed the canvas app in a Lightning component. 1. [Open the Developer Console.](https://help.salesforce.com/s/articleView?id=platform.code_dev_console_opening.htm) 2. Click **File** | **New** | **Lightning Component**. 3. Enter `myCanvasApp` in the `Name` field. 1. Copy and paste this code. ```xml <!-- myCanvasApp.cmp --> <aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" > <aura:attribute name="canvasParameters" type="string" /> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <aura:if isTrue="{!v.canvasParameters}"> <force:canvasApp developerName="Hello_World" height="400px" width="750px" parameters="{!v.canvasParameters}"/> </aura:if> </aura:component> ``` To verify the `developerName` value of your canvas app, in Setup, go to **External Client App Manager** and click on your app name. Then click the **Settings** tab and verify the **API Name**. 2. In the controller file, copy and paste this code. ```javascript ({ doInit : function(cmp, evt, helper) { var recordId = cmp.get("v.recordId"); cmp.set("v.canvasParameters", JSON.stringify({ recordId: recordId })); } }) ``` Save your changes. 6. Display the Lightning component on a record. 1. Navigate to the record page you want to customize, for example, a contact record page. 2. Click the gear icon and select **Edit Page.** 3. Find the myCanvasApp custom component and drag it to where you want it on the Lightning page. Save your changes. 4. Activate the page. Click **Assign as Org Default**, and then click **Next**. Your canvas app is now displayed on contact record pages. **See Also** - [Lightning Component Code Examples](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-aura-code-example.md) <!-- document id=a04c0fa7b26ec1fd28987f4887df6868cc848e9f3cc571454deaea1ba14e046c url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/dx/dx-setup/mobile-extensions-setup-android-studio.md --> # Set Up Android Studio Before you run previews in Android emulators, make sure that Android Studio is properly installed and configured. After you install Android Studio, test your environment with the `setup` command. If you’re using an existing Android Studio installation, run `setup` to verify that your installed environment meets Mobile Extensions requirements. ## Install Android Studio If you’ve already installed Android Studio, skip to “[Verify Your Android Studio Setup](#verify-your-android-studio-setup).” To install Android Studio, download and run the installer at [developer.android.com/studio](https://developer.android.com/studio). Android apps specify different API levels. According to the Android documentation: - “Minimum API level” is the lowest API level with which your app is compatible - “Target API level” is the highest API level against which you’ve designed and tested your app We recommend installing the latest available API level. If the latest level doesn't work as expected, try the next API level below. ![List of Android SDK platforms in Android Studio Preferences](https://developer.salesforce.com/media/mobile-offline/sdkmanager_apiversions.png) 1. In the Android Studio Welcome screen, click **Configure** | **SDK Manager**. 2. If you require previewing with additional API levels, download one or more **SDK Platforms**. We recommend the latest API level and one level below. For each required level: 1. Check the box next to its name. 2. Click Apply. Downloading new API versions can take several minutes. 3. If prompted, confirm each download, then accept the license agreement and click **Next**. 3. Select **SDK Tools**. 4. If the status of **Android SDK Command-line Tools (latest)** is “Not installed”, select **Android SDK Command-line Tools (latest)**, then click **Download**. ![Command-line tools download](https://developer.salesforce.com/media/mobile-offline/as_command_line_tools_select_download.png) Although the latest version is recommended, any version of the command-line tools is expected to work. 5. When the downloads are finished, click OK to dismiss the SDK Manager. ## Create a Virtual Device Now that you’ve installed the SDK, create an emulator for testing and debugging your apps. Let’s choose a system image that supports the latest API version and Google APIs. 1. In the Android Studio Welcome screen, click **Configure** | **AVD Manager**. 2. On the Your Virtual Devices page, click the plus symbol to **Add a new device**. Then, click **Create Virtual Device**. 3. Select a device definition, and click **Next**. 4. Under Select a System Image, select an image listing that supports the following criteria. **note:** In a new Android Studio installation, none of the images are downloaded. - **API Level:** 34 or higher - **ABI:** arm64-v8a - **Target:** Any image that Android Studio makes available by default ![Download button for Android 10.0 (Google Play) emulator](https://developer.salesforce.com/media/mobile-offline/avd_systemimage_x86images_download.png) 5. Click the **Download** button next to the Release Name. 6. After the download completes and you return to the System Image list, select the downloaded image and click **Next**. 7. In Verify Configuration, you can change the AVD name to any value that helps you identify the configuration. For other settings, you can accept the default values. 8. Click **Finish** to return to Your Virtual Devices. 9. To launch the emulator, click the Play button in your emulator’s listing. ## Verify Your Android Studio Setup During installation, Android Studio configures your system environment with standard Android paths and locations. The Mobile Extensions `setup` command checks your settings and reports issues to the command-line console. To verify that your environment is ready for Android previews, run the `setup` command: ```bash sf force:lightning:local:setup -p android ``` If `setup` reports any issues, use the following guidelines to correct them. **System Variables** The `ANDROID_HOME` variable is the starting point for all Android development operations. If this variable isn’t set or is incorrect, Mobile Extensions can’t use Android tools. You set `ANDROID_HOME` to point to the top-level directory of your Android SDK installation. On macOS, for example, this variable’s default value is `/Users/<user_name>/Library/Android/sdk`. If you’ve installed Android SDK in a custom directory, make sure that this path points to that location. **macOS X:** You can make these settings persistent by adding them to the ~/.bash_profile or similar startup file for your command shell. Configure `ANDROID_HOME` as follows. ```nolang export ANDROID_HOME=/Users/<your_user_name>/Library/Android/sdk ``` For Android, the Mobile Extensions plug-in requires the Java Development Kit (JDK) version used by Android Studio. Currently, this version is JDK 17. Your plug-in commands might fail if a `JAVA_HOME` system variable exists on your machine and points to a different JDK version, or if other applications in your system path use a different JDK version. You can find the correct JDK version installed with Android Studio’s Java runtime engine embedded in the Android Studio app. For example: ```nolang export JAVA_HOME="/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home" ``` See [the Android Developer documentation](https://developer.android.com/studio/intro/studio-config#jdk). **Windows:** In **System Properties** | **Advanced**, add the following variable definitions to either System Environment Variables or User Environment Variables. (For help with finding System Properties, see [www.imatest.com/docs/editing-system-environment-variables](https://www.imatest.com/docs/editing-system-environment-variables).) Variable: **`ANDROID_HOME`**. Value: C:\Users\<user>\AppData\Local\Android\Sdk. Variable: **`JAVA_HOME`**. Value: C:\Program Files\Android\Android Studio\jre. For Android, the Mobile Extensions plug-in requires the Java Development Kit (JDK) version used by Android Studio. If you set JAVA_HOME to a custom path that points to a different JDK version, the plug-in commands might fail. **Linux:** Set the following variable definitions in your ~/.profile file. Variable: **`ANDROID_HOME`**. Value: ~/Android/Sdk. Variable: **`JAVA_HOME`**. Value: /snap/android-studio/current/android-studio/jre. For Android, the Mobile Extensions plug-in requires the Java Development Kit (JDK) version used by Android Studio. Currently, this version is JDK 17. If you set JAVA_HOME to a custom path that points to a different JDK version, the plug-in commands might fail. **Android SDK Version:** One or more of: Android 9.0 (Pie), API Level 28, or higher. **Android Tools and Emulator:** Verify that you’ve installed the latest version of Android Emulator, Android SDK Platform-Tools, and Android SDK Command-line Tools. Check these versions in the SDK Tools section of the Android SDK Manager. In addition to the version ranges listed here, later stable versions of these tools are also expected to work. If you’ve changed any settings, rerun the `setup` command. <!-- document id=5534320d331bf5f0a79697eb90ec472e5dc39475d3a2753b66b202588e9bff59 url=/developer/current/en-us/platform/api-streaming/guides/api-streaming/code-examples/code-sample-auth-dev-test.md --> # Set Up Authentication for Developer Testing To set up authorization for developer testing: **important:** This authorization method is simple to use and recommended for testing your code quickly. However, we recommend that you use OAuth 2.0 in a production environment for more robust security. The OAuth authentication method with a connected app provides restricted access and other benefits. 1. Log in using the SOAP API `login()` and get the session ID. 2. Set up the HTTP authorization header using this session ID: ```nolang Authorization: Bearer sessionId ``` The CometD endpoint requires a session ID on all requests, plus any additional cookies set by the Salesforce server. For more information, see [Step 4: Use the Connector with Username and Password Login](https://developer.salesforce.com/docs/platform/api-streaming/guide/code-sample-java-add-source.md). <!-- document id=19d22b81e24c8abc2146fa4c97944b7410c29afcd42cd73dd84e0139e1cc2961 url=/developer/current/en-us/platform/api-streaming/guides/api-streaming/code-examples/code-sample-auth-oauth.md --> # Set Up Authorization with OAuth 2.0 Setting up OAuth 2.0 requires some configuration in the user interface and in other locations. If any of the steps are unfamiliar, you can consult the [REST API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm) or [OAuth 2.0 documentation](http://oauth.net/2/). The sample Java code in this chapter uses the Apache HttpClient library, which can be downloaded from [http://hc.apache.org/httpcomponents-client-ga/](http://hc.apache.org/httpcomponents-client-ga/). 1. In Salesforce Classic, from Setup, enter `Apps` in the `Quick Find` box, then select **Apps**. Or in Lightning Experience, enter `App` in the `Quick Find` box, then select **App Manager**. Click **New** in the Connected Apps related list to create a new connected app. The `Callback URL` you supply here is the same as your Web application's callback URL. If you work with Java, it’s usually a servlet. It must be secure: `http://` doesn’t work, only `https://`. For development environments, the callback URL is similar to `https://my-website/_callback`. When you save the connected app, its detail page is displayed. To view the consumer key and consumer secret, click **Manage Consumer Details**, and then verify your identity. **note:** The OAuth 2.0 specification uses “client” instead of “consumer.” Salesforce supports OAuth 2.0. The values here correspond to the following values in the sample code in the rest of this procedure: - `client_id` is the `Consumer Key` - `client_secret` is the `Consumer Secret` - `redirect_uri` is the `Callback URL`. An additional value you must specify is: the `grant_type`. For OAuth 2.0 callbacks, the value is `authorization_code` as shown in the sample. For more information about these parameters, see [Authorize Apps with OAuth](https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm) in _Salesforce Help_. If the value of `client_id` (or `consumer key`) and `client_secret` (or `consumer secret`) are valid, Salesforce sends a callback to the URI specified in `redirect_uri` that contains a value for `access_token.` 2. From your Java or other client application, make a request to the authentication URL that passes in `grant_type`, `client_id`, `client_secret`, `username`, and `password`. For example: ```nolang HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(baseURL); List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>(); parametersBody.add(new BasicNameValuePair("grant_type", password)); parametersBody.add(new BasicNameValuePair("client_id", clientId)); parametersBody.add(new BasicNameValuePair("client_secret", client_secret)); parametersBody.add(new BasicNameValuePair("username", "auser@example.com")); parametersBody.add(new BasicNameValuePair("password", "swordfish")); ``` **important:** Use the username-password authorization flow only if you’re handling your own credentials. Review the recommendations and restrictions for this authorization flow in [OAuth 2.0 Username-Password Flow for Special Scenarios](https://help.salesforce.com/s/articleView?id=xcloud.remoteaccess_oauth_username_password_flow.htm&type=5) in _Salesforce Help_. ## Example This example gets the session ID (authenticates), and then follows a resource, `https://MyDomainName.my.salesforce.com/id/00Dxxxxxxxxxxxx/005xxxxxxxxxxxx` contained in the first response to get more information about the user. ```nolang public static void oAuthSessionProvider(String loginHost, String username, String password, String clientId, String secret) throws HttpException, IOException { // Set up an HTTP client that makes a connection to REST API. DefaultHttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109); params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000); // Set the SID. System.out.println("Logging in as " + username + " in environment " + loginHost); String baseUrl = loginHost + "/services/oauth2/token"; // Send a post request to the OAuth URL. HttpPost oauthPost = new HttpPost(baseUrl); // The request body must contain these 5 values. List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>(); parametersBody.add(new BasicNameValuePair("grant_type", "password")); parametersBody.add(new BasicNameValuePair("username", username)); parametersBody.add(new BasicNameValuePair("password", password)); parametersBody.add(new BasicNameValuePair("client_id", clientId)); parametersBody.add(new BasicNameValuePair("client_secret", secret)); oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8)); // Execute the request. System.out.println("POST " + baseUrl + "...\n"); HttpResponse response = client.execute(oauthPost); int code = response.getStatusLine().getStatusCode(); Map<String, String> oauthLoginResponse = (Map<String, String>) JSON.parse(EntityUtils.toString(response.getEntity())); System.out.println("OAuth login response"); for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet()) { System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue())); } System.out.println(""); // Get user info. String userIdEndpoint = oauthLoginResponse.get("id"); String accessToken = oauthLoginResponse.get("access_token"); List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>(); qsList.add(new BasicNameValuePair("oauth_token", accessToken)); String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8); HttpGet userInfoRequest = new HttpGet(userIdEndpoint + "?" + queryString); HttpResponse userInfoResponse = client.execute(userInfoRequest); Map<String, Object> userInfo = (Map<String, Object>) JSON.parse(EntityUtils.toString(userInfoResponse.getEntity())); System.out.println("User info response"); for (Map.Entry<String, Object> entry : userInfo.entrySet()) { System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue())); } System.out.println(""); // Use the user info in interesting ways. System.out.println("Username is " + userInfo.get("username")); System.out.println("User's email is " + userInfo.get("email")); Map<String, String> urls = (Map<String, String>)userInfo.get("urls"); System.out.println("REST API url is " + urls.get("rest").replace("{version}", "68.0")); } ``` The output from this code resembles the following. ```nolang Logging in as auser@example.com in environment https://MyDomainName.my.salesforce.com POST https://MyDomainName.my.salesforce.com/services/oauth2/token... OAuth login response id = https://MyDomainName.my.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG issued_at = 1334961666037 instance_url = https://MyDomainName.my.salesforce.com access_token = 00D30000000ehjI!ARYAQHc.0Mlmz.DCg3HRNF.SmsSn5njPkry2SM6pb6rjCOqfAODaUkv5CGksRSPRb.xb signature = 8M9VWBoaEk+Bs//yD+BfrUR/+5tkNLgXAIwal1PMwsY= User info response user_type = STANDARD status = {created_date=2012-04-08T16:44:58.000+0000, body=Hello} urls = {sobjects=https://MyDomainName.my.salesforce.com/services/data/v{version}/sobjects/, feeds=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/feeds, users=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/users, query=https://MyDomainName.my.salesforce.com/services/data/v{version}/query/, enterprise=https://MyDomainName.my.salesforce.com/services/Soap/c/{version}/00D30000000ehjI, recent=https://MyDomainName.my.salesforce.com/services/data/v{version}/recent/, feed_items=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/feed-items, search=https://MyDomainName.my.salesforce.com/services/data/v{version}/search/, partner=https://MyDomainName.my.salesforce.com/services/Soap/u/{version}/00D30000000ehjI, rest=https://MyDomainName.my.salesforce.com/services/data/v{version}/, groups=https://MyDomainName.my.salesforce.com/services/data/v{version}/chatter/groups, metadata=https://MyDomainName.my.salesforce.com/services/Soap/m/{version}/00D30000000ehjI, profile=https://MyDomainName.my.salesforce.com/00530000003THy8AAG} locale = en_US asserted_user = true id = https://login.salesforce.com/id/00D30000000ehjIEAQ/00530000003THy8AAG nick_name = SampleNickname photos = {picture=https://MyDomainName.file.force.com/profilephoto/005/F, thumbnail=https://MyDomainName.file.force.com/profilephoto/005/T} display_name = Sample User first_name = Admin last_modified_date = 2012-04-19T04:35:29.000+0000 username = auser@example.com email = emailaddr@example.com organization_id = 00D30000000ehjIEAQ last_name = User utcOffset = -28800000 active = true user_id = 00530000003THy8AAG language = en_US Username is auser@example.com User's email is emailaddr@example.com REST API url is https://MyDomainName.my.salesforce.com/services/data/v68.0/ ``` <!-- document id=6bcd3d953bac7a721075c4c4475d3080848eef7f2a10ddfd0b77532f027d61c3 url=/developer/current/en-us/platform/platform-events/guides/platform-events/platform-events-subscribe-debug.md --> # Set Up Debug Logs for Event Subscriptions Debug logs for platform event triggers, event processes, and resumed flow interviews are created by Automated Process and are separate from their corresponding Apex code logs. For a platform event trigger with an overridden running user, debug logs are created by the specified user. The debug logs aren’t available in the Developer Console’s Log tab. - **[Add a Trace Flag Entry for the Default Automated Process User](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-subscribe-debug-autoproc.md)** To collect logs for an event subscription, add a trace flag entry for the Automated Process entity in Setup. - **[Add a Trace Flag Entry for the Overridden User](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-subscribe-debug-config-user.md)** To collect logs for an Apex trigger whose default running user is overridden, add a trace flag entry for the user in Setup. **See Also** - [*Salesforce Help*: Set Up Debug Logging](https://help.salesforce.com/articleView?id=code_add_users_debug_log.htm) <!-- document id=b8560580bfac47766ee298fa32d113f41ec5c69e0d70d7ccca57032643a9bab9 url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/dx/dx-setup/mobile-extensions-setup-ios-xcode.md --> # Set Up Xcode Before you run previews in iOS simulators, make sure that the latest version of Xcode is properly installed and configured. After you install Xcode, test your environment with the Mobile Preview `setup` command. If you’re using an existing Xcode installation, run the `setup` command to verify that your installed environment meets Mobile Extensions requirements. ## Install Xcode How you install Xcode depends on your version of macOS. We recommend using the latest version of macOS and Xcode. You can download and install Xcode from [developer.apple.com/downloads/more](https://developer.apple.com/support/xcode/). This site requires you to log in with your Apple ID. If you’ve already installed Xcode, skip to “[Verify Your iOS Setup](#verify-your-ios-setup).” ## Verify Your iOS Setup To verify that your new or existing Xcode environment is ready for iOS previews, run the Mobile Extensions `setup` command: ```bash sf force:lightning:local:setup -p ios ``` If `setup` reports any issues, follow these steps to correct them. 1. **Use the latest macOS:** To run Mobile Extensions for iOS, you have to use a Mac. Make sure it's using the latest version of macOS. 1. On your Mac, click **About This Mac** in the System menu. 2. Under **Overview**, look for the operating system name and version. Examples: “macOS Sonoma Version 14.5”. 2. **Verify that you’re running the latest version of Xcode.** 1. In Xcode, select **Xcode** | **About Xcode** and check the version number. 3. **Add an iOS simulator that runs the latest version of iOS.** 1. In **Xcode** | **Preferences**, select **Components**. In the Simulator list, installed simulators are marked with a blue check. The default simulator for your version of Xcode doesn’t appear in this list. 2. If none of your installed simulators use the latest version of iOS, check and install at least one updated iOS simulator. 4. **Final check:** Rerun the `setup` command: ```bash sf force:lightning:local:setup -p ios ``` 5. To see the list of installed virtual devices that Mobile Extensions recognizes on your machine, use the `device:list` command: ```bash sf force:lightning:local:device:list -p ios ``` <!-- document id=2b42a7f10bd9580536dda6cadde70197c5027ed9db830ef653ceb3ef0e1d3b9b url=/developer/current/en-us/platform/api-asynch/guides/api-asynch/code/asynch-api-code-set-up-client.md --> # Set Up Your Client Application The Bulk API uses HTTP GET and HTTP POST methods to send and receive XML or JSON content, so it’s simple to build clients in the language of your choice. This task uses a Java sample and the Salesforce Web Service Connector (WSC) toolkit provided by Salesforce to simplify development. WSC is a high-performing web service client stack implemented using a streaming parser. The toolkit has built-in support for the basic operations and objects used in the Bulk API. ## Before You Begin Review the library here: [https://github.com/forcedotcom/wsc](https://github.com/forcedotcom/wsc) To download the Salesforce WSC toolkit: 1. Browse to [http://mvnrepository.com/artifact/com.force.api/force-wsc](http://mvnrepository.com/artifact/com.force.api/force-wsc) or [https://repo1.maven.org/maven2/com/force/api/force-wsc/](https://repo1.maven.org/maven2/com/force/api/force-wsc/) 2. Navigate to the version of WSC that matches the API version you’re using. 3. Click `force-wsc-XX.X.X-uber.jar`, and save the file to a local directory. ## Next Steps The Bulk API doesn’t provide a login operation, so you must use the SOAP API to login. To download the partner WSDL and compile it to Java classes with the WSC toolkit: 1. Log in to your Developer Edition Salesforce account. You must log in as an administrator or as a user who has the “Modify All Data” permission. Logins are checked to ensure they are from a known IP address. For more information, see [Security and the API](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_concepts_security.htm) in the SOAP API Developer Guide. 2. From Setup, in the Quick Find box, enter `API`, then select **API**. 3. Right-click **Partner WSDL** to display your browser's save options, and save the partner WSDL to a local directory. 4. Compile the partner API code from the WSDL using the WSC compile tool: ```nolang java -classpath pathToJar\force-wsc-XX.X.X-uber.jar com.sforce.ws.tools.wsdlc pathToWSDL\wsdlFilename .\wsdlGenFiles.jar ``` For example, if `force-wsc-XX.X.X-uber.jar` is installed in `C:\salesforce\wsc`, and the partner WSDL is saved to `C:\salesforce\wsdl\partner`: ```nolang java -classpath C:\salesforce\wsc\force-wsc-XX.X.X-uber.jar com.sforce.ws.tools.wsdlc C:\salesforce\wsdl\partner\partner.wsdl .\partner.jar ``` The `force-wsc-XX.X.X-uber.jar` file and the generated `partner.jar` are the only libraries needed in the classpath for the code examples in the following sections. <!-- document id=ffec5fbd2b8c0c165d846ea55ad57a18d108aa2e64b5d7af63e8bd923c7fd0b6 url=/developer/current/en-us/platform/mobile-offline/guides/mobile-offline/dx/dx-setup/dx-set-up-dev-environment.md --> # Set Up Your Development Environment Before you can create your first Lightning web component (LWC), or test a LWC in a mobile app, you must set up your development environment for mobile components. The complete development environment for building Lightning web components for offline-enabled apps includes the following elements. - Salesforce CLI (SFDX) - Visual Studio Code (VS Code) - Salesforce Extensions for VS Code - Android Studio and a virtual device emulator - Apple Xcode and a virtual device simulator - Salesforce Mobile Extensions - A virtual device build for the relevant mobile app While you can eventually choose to replace or add tools to this list, start with these and add to them as you become more experienced. **note:** Don’t let Android Studio or Xcode intimidate you. You only need to use it to provision a device emulator (Android) or simulator (iOS). You don’t _need_ both Android Studio and Xcode. If you want both, great. If not, pick the one you’re most comfortable with. ## Installation Instructions We recommend the following installation sequence. Each link provides complete details for installing and configuring each of the different tools. - [Install and configure Android Studio](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup-android-studio.md) - [Install and configure Xcode](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup-ios-xcode.md) - [Install the Salesforce CLI](https://developer.salesforce.com/docs/platform/lwc/guide/get-started-cli.html) - [Install the Mobile Extensions](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup.md) - [Install VS Code](https://code.visualstudio.com/) - [Install Salesforce Extensions for VS Code](https://developer.salesforce.com/tools/vscode/en/vscode-desktop/install) - Download the latest virtual device build for the mobile app - For the Salesforce mobile app, use the standard virtual device builds, as described in [Preview Components in the Salesforce Mobile App](https://developer.salesforce.com/docs/platform/mobile-offline/dx-mobile-previews/dx-mobile-previews-salesforce-app.md). **note:** Your org must be enabled for LWC Offline before you can see or use LWC Offline features. - For the Field Service mobile app, the download link is posted in the [Trailblazer Community](https://trailblazers.salesforce.com/_ui/core/chatter/groups/GroupProfilePage?g=0F94S000000GwNL). - [Install a virtual device build](https://developer.salesforce.com/docs/platform/mobile-offline/dx-mobile-previews/dx-mobile-previews-salesforce-app.md#install-ios-and-android-virtual-device-builds) into a configured Android emulator or iOS simulator instance The [Develop a Lightning Web Component Quick Action](https://developer.salesforce.com/docs/platform/quickstart/quickstart-lwc-action.md) quick start provides hands-on instructions for setting up your development environment, and also for creating, deploying, and running your first LWC. - **[Install Mobile Extensions](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup.md)** To use Mobile Extensions, install the `lwc-dev-mobile` Salesforce CLI plug-in. After it’s installed, use it to check for the required Android and iOS configurations. If the plug-in finds problems, the command output gives you hints for how to fix your environment. After your environment is set up, preview your components from the command line or from Visual Studio Code. - **[Set Up Xcode](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup-ios-xcode.md)** Before you run previews in iOS simulators, make sure that the latest version of Xcode is properly installed and configured. After you install Xcode, test your environment with the Mobile Preview `setup` command. If you’re using an existing Xcode installation, run the `setup` command to verify that your installed environment meets Mobile Extensions requirements. - **[Set Up Android Studio](https://developer.salesforce.com/docs/platform/mobile-offline/guide/mobile-extensions-setup-android-studio.md)** Before you run previews in Android emulators, make sure that Android Studio is properly installed and configured. After you install Android Studio, test your environment with the `setup` command. If you’re using an existing Android Studio installation, run `setup` to verify that your installed environment meets Mobile Extensions requirements. <!-- document id=ca39b0f649b3419bbeee45a514cef2bce7a8b8250d17427a948491c5deb47736 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-user-password-post.md --> # Set User Password Sets a user’s password based on the specified user ID. The password provided in the request body replaces the user’s existing password. This resource is available in REST API version 24.0 and later. You can only set one password per request. The new password must conform to the password policies for the organization, otherwise an INVALID_NEW_PASSWORD error is returned. If the session doesn’t have permission to access the user information, an INSUFFICIENT_ACCESS error is returned. ## Syntax **URI:** `/services/data/vXX.X/sobjects/User/userId/password` **Formats:** JSON, XML **HTTP Method:** POST **Authentication:** `Authorization: Bearer token` **Parameters:** None required ## Example For examples of getting password information, setting a password, and resetting a password, see [Manage User Passwords](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-user-password.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=1d6241cb58c5b85d1f2f18b423f9de034ed3d97defe7687070809b4b26dbcfda url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-component-set.md --> # set() Sets the value referenced using property syntax. ## Signature `set(String key, Object value)` ## Parameters **_key_:** Type: `String`. The data key to set on the component; for example, `cmp.set("v.key","value")`. **_value_:** Type: `Object`. The value to set. **See Also** - [get()](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-jsapi-dollara-get.md) <!-- document id=98cbdd3ce98bdeb6fc1c8d6bc537a58cc61f18270ad918476dbca725af63a0b9 url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-dollara-set.md --> # set() Sets a value on the specified global value provider using property syntax. ## Signature `set (String key, Object value)` ## Parameters **_key_:** Type: `String`. The data key to change on the global value provider. **_value_:** Type: `Object`. The value to set for the key. If the global value provider doesn’t implement `set()`, this method throws an exception. <!-- document id=050631c561137b7a28ee165974a642688268fffa04c026f9af43c785740274ff url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setabortable.md --> # setAbortable() 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. For example, a save or edit action should not be set as abortable to ensure that it’s always sent to the server even if the component is deleted. Setting an action as abortable can’t be undone. ## Signature `setAbortable()` **See Also** - [Abortable Actions](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-abortable-actions.md) <!-- document id=9d1d7aff48c672100401cc8139039843fb66aeb5bbdbb0da187327b42eef169f url=/developer/current/en-us/platform/case_feed_dev_guide/guides/quickactions/quickaction-api-setactionfieldvalues.md --> # setActionFieldValues Allows custom components to select a quick action on a record page and then specify field values for that action. Because this method also selects the quick action, you don't need to use the `selectAction` method. To submit the quick action updates, pass `submitOnSuccess` as `true`. ## Arguments |Name|Type|Description| |----|----|-----------| |actionName|string|The name of the quick action that you want to access.| |parentFields|Object|Optional. The fields that you want to update on the current record. For example, if you want to set field values on the Email quick action on the case record page, the case object is the parent record.| |targetFields|Object|The fields that you want to update on the quick action.| |submitOnSuccess|boolean|Optional. Set to true if you want to save and submit the quick action after setting the field values. Default is false.| The actionName parameter starts with the Salesforce object, followed by the quick action name. For example: ```nolang actionName: "Case.UpdateCase" ``` The parentFields and targetFields objects contain a list of field names with values for each field. Each field can optionally specify the insertion behavior using the `insertType` key, which can be `replace` (default), `cursor`, or `begin`. For example: ```nolang var parentFields = { Status: {value: "Closed"}, Subject: {value: "Case subject", insertType: "cursor"} } var targetFields = { ToAddress: {value: "to@to.com"}, TextBody: {value: "the text body", insertType: "cursor"} } ``` We recommend that you don’t use this API with the following items: - Read-only fields - Encrypted fields - Fields within social actions ## Response Returns a Promise. Success resolves to a response object. The Promise is rejected on error response. ```nolang success: boolean, actionName: "LogACall", unavailableAction: boolean, targetFieldErrors: [{ Status: {message: "error"}, Subject: {message: "error", }], errors: [] ``` <!-- document id=386f22a57953de856cd9ccd526d44c97e2c97459b2ff8503fabf3f056efcea1d url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setbackground.md --> # setBackground() 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. ## Signature `setBackground()` <!-- document id=27842323f18a4eeff75140269c70ae67c688db6856ae8ab0d8d0ec4111d116cf url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setcallback.md --> # setCallback() Sets the callback function that is executed after an Apex action returns. ## Signature `setCallback (Object scope, function callback, String name)` ## Parameters **_scope_:** Type: `Object`. The scope in which the function is executed. Always set this parameter to the keyword `this`. **_callback_:** Type: `function`. The callback to invoke after the Apex action returns. **_name_:** Type: `String`. Defaults to "ALL" which registers callbacks for the "SUCCESS", "ERROR", and "INCOMPLETE" states. **See Also** - [Calling a Server-Side Action](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-actions-call.md) - [Action States](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-actions-states.md) <!-- document id=fb5c3b292dced4f655e1e0ac7c069d4cfad336fa2196cba92559865ecda77669 url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setparam.md --> # setParam() Sets a single parameter for an action. Use parameters to pass data to an Apex action. ## Signature `setParam (String key, Object value)` ## Parameters **_key_:** Type: `String`. The parameter name. **_value_:** Type: `Object`. The parameter value. **See Also** - [Calling a Server-Side Action](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-actions-call.md) <!-- document id=f9b340258d46cf98d80fe147320b9bcd99dbbf5e36511c17947f599a6f05a545 url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-event-setparam.md --> # setParam() Sets a parameter for an event. This method doesn’t modify an event that has already been fired. ## Signature `setParam(String key, Object value)` ## Parameters **_key_:** Type: `String`. The name of the parameter. **_value_:** Type: `Object`. The value of the parameter. <!-- document id=4d4eff618878c203ca560bb1276e9cbd2a4b9d60aacf06e10e4234ab43e9057f url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setparams.md --> # setParams() Sets parameters for an action. Use parameters to pass data to an Apex action. ## Signature `setParams (Object config)` ## Parameters **_config_:** Type: `Object`. The key-value pairs for action parameters. For example `{ "record": id, "name": name}.` **See Also** - [Calling a Server-Side Action](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-actions-call.md) <!-- document id=bc88c7ac12f14797df9ff561040fae07c3f7f0a1dafe4684dce54ef91488a6fe url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-event-setparams.md --> # setParams() Sets parameters for an event. This method doesn’t modify an event that has already been fired. ## Signature `setParams(Object config)` ## Parameters **_config_:** Type: `Object`. The event’s parameter. <!-- document id=e683e0c4ff78c00e5cef2db462fd109ad7cd2738eecaaf34016a107da7bf8d8f url=/developer/current/en-us/platform/api/guides/api/utils/sforce-api-calls-setpassword.md --> # `setPassword()` Sets the specified user's password to the specified value. ## Syntax ```java SetPasswordResult setPasswordResult = connection.setPassword(ID userID, string password); ``` ## Usage Use [`setPassword()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-setpassword.md) to change the password of a [User](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) or [SelfServiceUser](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_selfserviceuser.htm) to a value that you specify. For example, a client application prompts a user to specify a different password, and then invokes `setPassword()` for an admin to change the user's password. Use [`resetPassword()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-resetpassword.md) instead if you want to reset the password with a random value generated by the API. This call can be used to allow users to change their own passwords, as long as their org’s Password Policies setting **Allow use of setPassword() API for self-resets** is enabled. Otherwise, use [`changeOwnPassword()`](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-changeownpassword.md), which is more secure because it verifies the user’s current password before allowing the change. Your client application must be logged in with sufficient access rights to change the password for the specified user. For more information, see [Factors that Affect Data Access](https://developer.salesforce.com/docs/platform/api/calls/calls.md). For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616). This call can use the session ID returned in [LoginResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) if the password has expired. For more information, see [`passwordExpired`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md). ## Sample Code—Java This sample accepts user ID and password parameters, which it uses in the `setPassword()` call to set the password of the specified user. <!-- otherprops: java set_clipboard --> ```codesegment public void doSetPassword(String userId, String newPasswd) { try { SetPasswordResult result = connection.setPassword(userId, newPasswd); System.out.println("The password for user ID " + userId + " changed to " + newPasswd); } catch (ConnectionException ce) { ce.printStackTrace(); } } ``` ## Sample Code—C# This sample accepts user ID and password parameters, which it uses in the `setPassword()` call to set the password of the specified user. <!-- otherprops: c_sharp set_clipboard --> ```codesegment public void doSetPassword(String userId, String newPasswd) { try { SetPasswordResult result = binding.setPassword(userId, newPasswd); Console.WriteLine("The password for user ID " + userId + " changed to " + newPasswd); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + "\n" + e.StackTrace); } } ``` ## Arguments |Name|Type|Description| |----|----|-----------| |`userID`|ID|ID of the [User](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm) or [SelfServiceUser](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_selfserviceuser.htm) whose password you want to reset. For information on IDs, see [ID Field Type](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/field_types.htm#i1435616).| |`password`|string|New password to use for the specified user.| ## Response SetPasswordResult (empty) ## Fault [`InvalidIdFault`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md) [`UnexpectedErrorFault`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-concepts-core-data-objects.md) **See Also** - [resetPassword()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-resetpassword.md) - [Utility Calls](https://developer.salesforce.com/docs/platform/api/guide/utility-calls.md) - [changeOwnPassword()](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-calls-changeownpassword.md) <!-- document id=603913345294c20396632c6f7d160e5f7a62106683748623cf8959b750016c9c url=/developer/current/en-us/platform/aura-platform/guides/aura/ref-jsapi/ref-jsapi-action-setstorable.md --> # setStorable() 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. **note:** Client-side storage is automatically configured in Lightning Experience and the Salesforce mobile app. A component shouldn’t assume a cache duration because it may change as we optimize the platform. ## Signature `setStorable (Object config)` ## Parameters **_config_** Type: `Object` An optional configuration map of key-value pairs representing the storage options and values to set. You can only set the `ignoreExisting` property. Set `ignoreExisting` to `true` to bypass the cache. The default value is `false`. This property is useful when you know that any cached data is invalid, such as after a record modification. This property should be used rarely because it explicitly defeats caching. **See Also** - [Storable Actions](https://developer.salesforce.com/docs/platform/aura-platform/controllers-server/controllers-server-storable-actions.md) <!-- document id=af60d704ca495761d5d36a02d8123f3dedc1680347647006090ff108617f73a6 url=/developer/current/en-us/platform/aura-platform/guides/aura/ref/ref-tag-set-attr-super.md --> # Setting Attributes Inherited from a Super Component Use `<aura:set>` in the markup of a sub component to set the value of an inherited attribute. Let's look at an example. Here is the `c:setTagSuper` component. <!-- otherprops: set_clipboard --> ```nolang <!--c:setTagSuper--> <aura:component extensible="true"> <aura:attribute name="address1" type="String" /> setTagSuper address1: {!v.address1}<br/> </aura:component> ``` `c:setTagSuper` outputs: ```nolang setTagSuper address1: ``` The `address1` attribute doesn't output any value yet as it hasn't been set. Here is the `c:setTagSub` component that extends `c:setTagSuper`. <!-- otherprops: set_clipboard --> ```nolang <!--c:setTagSub--> <aura:component extends="c:setTagSuper"> <aura:set attribute="address1" value="808 State St" /> </aura:component> ``` `c:setTagSub` outputs: ```nolang setTagSuper address1: 808 State St ``` `sampleSetTagEx c:setTagSub` sets a value for the `address1` attribute inherited from the super component, `c:setTagSuper`. **warning:** This usage of `<aura:set>` works for components and abstract components, but it doesn’t work for interfaces. For more information, see [Setting Attributes Inherited from an Interface](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-tag-set-attr-intf.md). If you’re using a component by making a reference to it in your component, you can set the attribute value directly in the markup. For example, `c:setTagSuperRef` makes a reference to `c:setTagSuper` and sets the `address1` attribute directly without using `aura:set`. <!-- otherprops: set_clipboard --> ```nolang <!--c:setTagSuperRef--> <aura:component> <c:setTagSuper address1="1 Sesame St" /> </aura:component> ``` `c:setTagSuperRef` outputs: <!-- otherprops: set_clipboard --> ```nolang setTagSuper address1: 1 Sesame St ``` **See Also** - [Component Body](https://developer.salesforce.com/docs/platform/aura-platform/components/components-body.md) - [Inherited Component Attributes](https://developer.salesforce.com/docs/platform/aura-platform/oo/oo-cmp-attributes.md) - [Setting Attributes on a Component Reference](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-tag-set-cmp-ref.md) <!-- document id=8efd58e532c0b9b5ea670c90eaf231ed16e9023272fbe9b96500d278fc1314df url=/developer/current/en-us/platform/aura-platform/guides/aura/ref/ref-tag-set-attr-intf.md --> # Setting Attributes Inherited from an Interface To set the value of an attribute inherited from an interface, redefine the attribute in the component and set its default value. Let’s look at an example with the c:myIntf interface. ```nolang <!--c:myIntf--> <aura:interface> <aura:attribute name="myBoolean" type="Boolean" default="true" /> </aura:interface> ``` This component implements the interface and sets `myBoolean` to `false`. <!-- otherprops: set_clipboard --> ```nolang <!--c:myIntfImpl--> <aura:component implements="c:myIntf"> <aura:attribute name="myBoolean" type="Boolean" default="false" /> <p>myBoolean: {!v.myBoolean}</p> </aura:component> ``` <!-- document id=527c3c6063c562955f98976c84252dbe4b7bb502572b6f33303bf438eea7e53b url=/developer/current/en-us/platform/aura-platform/guides/aura/ref/ref-tag-set-cmp-ref.md --> # Setting Attributes on a Component Reference When you include another component, such as `<lightning:button>`, in a component, we call that a component reference to `<lightning:button>`. You can use `<aura:set>` to set an attribute on the component reference. For example, if your component includes a reference to `<lightning:button>`: <!-- otherprops: set_clipboard --> ```nolang <lightning:button label="Save"> <aura:set attribute="variant" value="brand"/> </lightning:button> ``` This is equivalent to: <!-- otherprops: set_clipboard --> ```nolang <lightning:button label="Save" variant="brand" /> ``` The latter syntax without `aura:set` makes more sense in this simple example. You can also use this simpler syntax in component references to set values for attributes that are inherited from parent components. `aura:set` is more useful when you want to set markup as the attribute value. For example, this sample specifies the markup for the `else` attribute in the `aura:if` tag. <!-- otherprops: set_clipboard --> ```nolang <aura:component> <aura:attribute name="display" type="Boolean" default="true"/> <aura:if isTrue="{!v.display}"> Show this if condition is true <aura:set attribute="else"> <lightning:button label="Save" onclick="{!c.saveRecord}" /> </aura:set> </aura:if> </aura:component> ``` **See Also** - [Setting Attributes Inherited from a Super Component](https://developer.salesforce.com/docs/platform/aura-platform/guide/ref-tag-set-attr-super.md) <!-- document id=86276d8a667a79bd6f635e7cd2860f69770aabce20991b3d72398db1ae489f65 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/styling/pages-html-features-pass-through-attributes.md --> # Setting Custom HTML Attributes on Visualforce Components You can add arbitrary attributes to many Visualforce components that are “passed through” to the rendered HTML. This is useful, for example, when using Visualforce with JavaScript frameworks, such as jQuery Mobile, AngularJS, and Knockout, which use `data-*` or other attributes as hooks to activate framework functions. Pass-through attributes can also be used to improve usability with HTML5 features such as `placeholder` “ghost” text, `pattern` client-side validation, and `title` help text attributes. **important:** The behavior of HTML5 features is determined by the user’s browser, not Visualforce, and varies considerably from browser to browser. If you want to use these features, test early and often on every browser and device you plan to support. To add a pass-through attribute to, for example, an `<apex:outputPanel>` component, prefix the attribute with “html-” and set the attribute value as normal. ```visualforce <apex:page showHeader="false" standardStylesheets="false" doctype="html-5.0"> <apex:outputPanel layout="block" html-data-role="panel" html-data-id="menu"> <apex:insert name="menu"/> </apex:outputPanel> <apex:outputPanel layout="block" html-data-role="panel" html-data-id="main"> <apex:insert name="main"/> </apex:outputPanel> </apex:page> ``` This produces the following HTML output. ```html <!DOCTYPE HTML> <html> <head> ... </head> <div id="..." data-id="menu" data-role="panel"> <!-- contents of menu --> </div> <div id="..." data-id="main" data-role="panel"> <!-- contents of main --> </div> </html> ``` Every attribute that begins with “html-” is passed through to the resulting HTML, with the “html-” removed. **note:** Pass-through attributes that conflict with built-in attributes for the component generate a compilation error. Pass-through attributes are supported by the following Visualforce components. - `<apex:column>` - `<apex:commandButton>` - `<apex:commandLink>` - `<apex:component>` - `<apex:dataTable>` - `<apex:form>` - `<apex:iframe>` - `<apex:image>` - `<apex:includeScript>` - `<apex:input>` - `<apex:inputCheckbox>` - `<apex:inputField>` - `<apex:inputHidden>` - `<apex:inputSecret>` - `<apex:inputText>` - `<apex:inputTextarea>` - `<apex:messages>` - `<apex:outputField>` - `<apex:outputLabel>` - `<apex:outputLink>` - `<apex:outputPanel>` - `<apex:outputText>` - `<apex:page>` - `<apex:pageBlock>` - `<apex:pageBlockButtons>` - `<apex:pageBlockSection>` - `<apex:pageBlockSectionItem>` - `<apex:pageBlockTable>` - `<apex:panelBar>` - `<apex:panelBarItem>` - `<apex:panelGrid>` - `<apex:sectionHeader>` - `<apex:selectCheckboxes>` - `<apex:selectList>` - `<apex:selectOption>` - `<apex:selectOptions>` - `<apex:selectRadio>` - `<apex:stylesheet>` - `<apex:tab>` - `<apex:tabPanel>` For additional information about individual components, including the specifics of where pass-through attributes are added to their rendered HTML, see [Standard Visualforce Component Reference](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref.md). To create HTML markup that can’t be generated using components that support pass-through attributes, combine Visualforce tags with static HTML. For example, to create a jQuery Mobile `listview`, combine the `<apex:repeat>` tag with the HTML tags you need. ```visualforce <ul data-role="listview" data-inset="true" data-filter="true"> <apex:repeat value="{! someListOfItems}" var="item"> <li><a href="#">{! item.Name}</a></li> </apex:repeat> </ul> ``` Pass-through attributes aren’t supported in dynamic Visualforce. **See Also** - [Using a Custom Doctype](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-doctype.md) <!-- document id=1f486535a3483bf4c4233f86027fdf82c344000e03069aec93805467f428e64c url=/developer/current/en-us/platform/aura-platform/guides/aura/labels/labels-parentcmp.md --> # Setting Label Values via a Parent Attribute Setting label values via a parent attribute is useful if you want control over labels in child components. Let’s say that you have a container component, which contains another component, inner.cmp. You want to set a label value in inner.cmp via an attribute on the container component. This can be done by specifying the attribute type and default value. You must set a default value in the parent attribute if you are setting a label on an inner component, as shown in the following example. This is the container component, which contains a default value `My Label` for the `_label` attribute . <!-- otherprops: set_clipboard --> ```nolang <aura:component> <aura:attribute name="_label" type="String" default="My Label"/> <lightning:button label="Set Label" aura:id="button1" onclick="{!c.setLabel}"/> <auradocs:inner aura:id="inner" label="{!v._label}"/> </aura:component> ``` This inner component contains a text area component and a `label` attribute that’s set by the container component. <!-- otherprops: set_clipboard --> ```nolang <aura:component> <aura:attribute name="label" type="String"/> <lightning:textarea aura:id="textarea" name="myTextarea" label="{!v.label}"/> </aura:component> ``` This client-side controller action updates the label value. <!-- otherprops: set_clipboard --> ```javascript ({ setLabel:function(cmp) { cmp.set("v._label", 'new label'); } }) ``` When the component is initialized, you’ll see a button and a text area with the label `My Label`. When the button in the container component is clicked, the `setLabel` action updates the label value in the inner component. This action finds the `label` attribute and sets its value to `new label`. **See Also** - [Input Component Labels](https://developer.salesforce.com/docs/platform/aura-platform/guide/labels-overview.md) - [Component Attributes](https://developer.salesforce.com/docs/platform/aura-platform/components/components-attributes.md) <!-- document id=6322bd82abcbf033ae06ff44eddea4de589c3a543e5ad04c97b18196c9875713 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/quick-start/pages-quick-start-query-params-setting.md --> # Setting Query String Parameters in Links You can set query string parameters in links to pages by constructing the link URL manually, or by using `<apex:param>` tags within the `<apex:outputLink>` tag. For example, both of the following examples create identical links to an external page: ```visualforce <apex:outputLink value="http://google.com/search?q={!account.name}"> Search Google </apex:outputLink> ``` ```visualforce <apex:outputLink value="http://google.com/search"> Search Google <apex:param name="q" value="{!account.name}"/> </apex:outputLink> ``` The latter method, which uses `<apex:param>` tags instead of manually creating the URL, is preferable for stylistic reasons. **note:** In addition to `<apex:outputLink>`, use `<apex:param>` to set request parameters for `<apex:commandLink>`, and `<apex:actionFunction>`. <!-- document id=31d11b77813e7c64f88112159f97dc4045a3d6ef30473c6c5c0355b8985974ba url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/controller/pages-controller-readonly-context-pagelevel.md --> # Setting Read-Only Mode for an Entire Page To enable read-only mode for an entire page, set the `readOnly` attribute on the `<apex:page>` component to `true`. For example, here’s a simple page that is processed in enable read-only mode: <!-- otherprops: apex_page --> ```markup <apex:page controller="SummaryStatsController" readOnly="true"> <p>Here is a statistic: {!veryLargeSummaryStat}</p> </apex:page> ``` The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page: <!-- otherprops: apex_code --> ```controller public class SummaryStatsController { public Integer getVeryLargeSummaryStat() { Integer closedOpportunityStats = [SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true]; return closedOpportunityStats; } } ``` Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In enable read-only mode, this limit is relaxed to allow querying up to 1,000,000 rows. In addition to querying many more rows, the `readOnly` attribute also increases the maximum number of items in a collection that can be iterated over using components such as `<apex:dataTable>`, `<apex:dataList>`, and `<apex:repeat>`. This limit increased from 1,000 items to 10,000. Here’s a simple controller and page demonstration: <!-- otherprops: apex_code --> ```controller public class MerchandiseController { public List<Merchandise__c> getAllMerchandise() { List<Merchandise__c> theMerchandise = [SELECT Name, Price__c FROM Merchandise__c LIMIT 10000]; return(theMerchandise); } } ``` <!-- otherprops: apex_page --> ```markup <apex:page controller="MerchandiseController" readOnly="true"> <p>Here is all the merchandise we have:</p> <apex:dataTable value="{!AllMerchandise}" var="product"> <apex:column> <apex:facet name="header">Product</apex:facet> <apex:outputText value="{!product.Name}" /> </apex:column> <apex:column> <apex:facet name="header">Price</apex:facet> <apex:outputText value="{!product.Price__c}" /> </apex:column> </apex:dataTable> </apex:page> ``` While Visualforce pages that use enable read-only mode for the entire page can’t use data manipulation language (DML) operations, they can call getter, setter, and action methods that affect form and other user interface elements on the page, make additional read-only queries, and so on. <!-- document id=ccd4dea25dbc736a2b0cfac2e82b3dc81f628ede569cee6a36939410478d9153 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/controller/pages-controller-readonly-context-methodlevel.md --> # Setting Read-Only Mode for Controller Methods Visualforce controller methods can, with some important limitations, use the Apex `ReadOnly` annotation, even if the page itself isn’t in read-only mode. Visualforce controller methods with the `@ReadOnly` annotation automatically take advantage of read-only mode.. However, restrictions on the `@ReadOnly` annotation means that, for Visualforce controller methods, a read-only method must also have the `@RemoteAction` annotation. The `@RemoteAction` annotation requires that the method be: - Either `global` or `public` - `static` Enabling read-only mode. by using the `@ReadOnly` annotation must be done on the top level method call. If the top level method call doesn’t have the`@ReadOnly` annotation, the normal restrictions on maximum queried rows are enforced for the entire request, even if secondary methods are annotated with `@ReadOnly`. Using the `@ReadOnly` annotation on a controller method allows you to retrieve a larger collection of records as the result of a Visualforce expression. However, it doesn’t increase the maximum number of items in a collection for iteration components. If you want to iterate over larger collections of results, you need to enable read-only mode. for the entire page. **See Also** - [Setting Read-Only Mode for an Entire Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-readonly-context-pagelevel.md) - [*Apex Developer Guide*: ReadOnly Annotation](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_ReadOnly.htm) <!-- document id=14f6ab827aa887bcb7611d2fc4f041310347012bd1c235189934f96dddb2eebb url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/quick-start/pages-input-field-tabindex.md --> # Setting the Tab Order for Fields in a Form Visualforce forms have a “natural order” for tabbing through the input fields: left-to-right, top-to-bottom. For some forms, this might not be the most efficient or accessible arrangement. You can use the `tabIndex` and `tabOrderHint` attributes on input and other components in your page to change the tab order to anything you’d like. Here is a simple example that uses the `tabOrderHint` attribute to control the tab order. <!-- otherprops: set_clipboard --> ```apex_page <apex:page standardController="Account"> <apex:form> <apex:pageBlock title="Edit Account: {!Account.Name}"> <apex:pageBlockSection title="Account Details" columns="1"> <apex:inputField value="{!Account.Name}" tabOrderHint="4"/> <apex:inputField value="{!Account.Website}" tabOrderHint="3"/> <apex:inputField value="{!Account.Industry}" tabOrderHint="2"/> <apex:inputField value="{!Account.AnnualRevenue}" tabOrderHint="1"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> ``` **note:** Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: ```nolang https://MyDomain_login_URL/apex/myPage?id=001x000xxx3Jsxb ``` [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. Notice that when you display this page and press TAB, the active field changes in the reverse order than you would normally expect. ## Using `tabIndex` and `tabOrderHint` The `tabOrderHint` attribute is used as a hint when calculating the value to set for the `tabindex` value of the rendered HTML element or elements. It’s used to indicate the *relative* order in which the field is selected compared to other page components. This value must be an integer between 1 and 3276, or an expression which evaluates to an integer value in the same range. The tab order begins with component 1 being the first component selected when a user presses TAB. The `tabIndex` attribute is used to directly set the `tabindex` value of the rendered HTML element. It’s an *absolute* index setting the order in which the field is selected, compared to other page components. This value must be an integer between 0 and 32767, or an expression which evaluates to an integer value in the same range. The tab order begins with component 0 being the first component selected when a user presses TAB. The `tabOrderHint` attribute is available on only the `<apex:inputField>` component. The `tabIndex` attribute can be set on the following Visualforce components. - `<apex:commandButton>` - `<apex:commandLink>` - `<apex:inputCheckbox>` - `<apex:inputFile>` - `<apex:inputSecret>` - `<apex:inputText>` - `<apex:inputTextarea>` - `<apex:outputLabel>` - `<apex:outputLink>` - `<apex:selectCheckboxes>` - `<apex:selectList>` - `<apex:selectRadio>` When mixing `<apex:inputField>` with components that use the `tabIndex` attribute to set the tab order, you can multiply the `tabOrderHint` by 10 to get the approximate equivalent value of the `tabIndex` for that field. Use this to manually calculate equivalent values to set the appropriate attribute on each of the components in such a way as to set the desired tab order for all elements on the page. <!-- document id=e36391b9b3689971b3d94f9423c76a5f8583bc2b7916a46609508c752e1c8484 url=/developer/current/en-us/platform/salesforce-developer-environment-dotnet-tipsheet/guides/tip-sheets/salesforce-developer-environment-tipsheet/salesforce-developer-environment-remoteaccess.md --> # Setting Up External Client App Access (REST-Based APIs) Because Salesforce REST APIs use OAuth authentication, create an external client app to integrate your application with Salesforce. An external client app integrates an application with Salesforce using APIs. External client apps use standard SAML and OAuth protocols to authenticate, provide single sign-on, and provide tokens for use with Salesforce APIs. In addition to standard OAuth capabilities, exernal client apps allow Salesforce admins to set various security policies and have explicit control over who can use the corresponding apps. Specify basic information about your app. See [Configure Basic Connected App Settings ](https://help.salesforce.com/articleView?id=connected_app_create_basics.htm)in *Salesforce Help*. Next, provide OAuth settings. See [Enable OAuth Settings for API Integration](https://help.salesforce.com/s/articleView?id=xcloud.external_integrations.htm) in *Salesforce Help*. For more information, see [Create a Connected App](https://help.salesforce.com/articleView?id=connected_app_create.htm) in *Salesforce Help*. <!-- document id=aada3eaa3e993f3f4a527855151f35c6083a425d686977dc77fa5c042c7bb587 url=/developer/current/en-us/platform/api/guides/api/om/sforce-api-om-outboundmessaging-setting-up.md --> # Setting Up Outbound Messaging Before you can use outbound messaging, you must set it up via the Salesforce user interface. - [Setting Up User Profiles](#setting-up-user-profiles) - [Defining Outbound Messaging](#defining-outbound-messaging) - [Downloading the Salesforce Client Certificate](#downloading-the-salesforce-client-certificate) - [Viewing Outbound Messages](#viewing-outbound-messages) - [Tracking Outbound Message Status](#tracking-outbound-message-status) ## Setting Up User Profiles It’s possible to create circular changes with outbound messaging. For example, if a user is performing integrations that trigger workflow, and the workflow actions trigger account updates, those account updates trigger new workflow, and so on. To prevent these circular changes, you can disable a user’s ability to send outbound messages. Here’s another example of a circular change scenario. 1. You configure an outbound message to include a [sessionId](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) and specify a user in the **User to send as** field. The user doesn’t have outbound messaging disabled. 2. A change in a contact record triggers an outbound message from the specified user, with the [sessionId](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) to your outbound message listener. 3. Your outbound message listener calls the Lightning Platform API and updates the same contact record which triggered the outbound message. 4. The update triggers an outbound message. 5. Your outbound message listener updates the record. 6. The update triggers an outbound message. 7. Your outbound message listener updates the record. To disable outbound message notifications for a user, deselect **Send Outbound Messages** in the user’s [Profile](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_profile.htm). We recommend specifying a single user to respond to outbound messages and disabling this user's ability to send outbound messages. ## Defining Outbound Messaging To define outbound messages, use this procedure in the Salesforce user interface: 1. From Setup, enter `Outbound Messages` in the `Quick Find` box, then select **Outbound Messages** under Workflow Actions. 2. Click **New Outbound Message**. 3. Choose the object that has the information you want included in the outbound message, and click **Next**. 4. Configure the outbound message. 1. Enter a name and description for this outbound message. 2. Enter an endpoint URL for the recipient of the message. Salesforce sends a SOAP message to this endpoint. For security reasons, Salesforce restricts the outbound ports you can specify to one of the following: - 80: This port only accepts HTTP connections. - 443: This port only accepts HTTPS connections. - 1024–66535 (inclusive): These ports accept HTTP or HTTPS connections. 3. Select the Salesforce user to use when sending the message by specifying a username in the **User to send as** field. The chosen user controls data visibility for the message that is sent to the endpoint. 4. Select **Send Session ID** if you want a [`sessionId`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) to be included in the outbound message. Include the [`sessionId`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) in your message if you intend to make API calls back to Salesforce from your listener. The [`sessionId`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) represents the user defined in the previous step and not the user who triggered the workflow. 5. Select the fields you want included in the outbound message and click **Add**. 5. Click **Save**, and review the outbound message detail page: - The `API Version` field is automatically generated and set to the current API version when the outbound message was created. This API version is used in API calls back to Salesforce using the enterprise or partner WSDL. The `API Version` can only be modified by using the Metadata API. - Click **Click for WSDL** to view the WSDL associated with this message. The WSDL is bound to the outbound message and contains the instructions about how to reach the endpoint service and what data is sent to it. **note:** If you don’t have these options, your org doesn’t have outbound messaging enabled. Contact Salesforce to enable outbound messaging for your org. ## Downloading the Salesforce Client Certificate Your application (endpoint) server's SSL/TLS can be configured to require client certificates (two-way SSL/TLS), in order to validate the identity of the Salesforce server when it takes the role of client to your server. You can download the Salesforce client certificate from the Salesforce application user interface. This certificate is the client certificate that Salesforce sends with each outbound message for authentication. 1. From Setup, enter `API` in the `Quick Find` box, then select **API**. 2. On the API WSDL page, click **Manage API Client Certificate**. 3. On the Certificate and Key Management page, in the API Client Certificate section, click the **API Client Certificate**. 4. On the Certificates page, click **Download Certificate**. The .crt file is saved in the download location specified in your browser. Import the downloaded certificate into your application server, and configure your application server to request the client certificate. The application server then checks that the certificate used in the SSL/TLS handshake matches the one you downloaded. **note:** Your application (endpoint) server must send any intermediate certificates in the certificate chain, and the certificate chain must be in the correct order. The correct order is: 1. Server certificate 2. Intermediate certificate that signed the server certificate if the server certificate wasn’t signed directly by a root certificate 3. Intermediate certificate that signed the certificate in step 2 4. Any remaining intermediate certificates Don’t include the root certificate authority certificate. The root certificate isn’t sent by your server. Salesforce already has its own list of trusted certificates on file, and a certificate in the chain must be signed by one of those root certificate authority certificates. ## Viewing Outbound Messages To view existing outbound messages, from Setup, enter `Outbound Messages` in the `Quick Find` box, then select **Outbound Messages** in the Salesforce user interface. - Click **New Outbound Message** to define a new outbound message. - Click **View Message Delivery Status** to track the status of an outbound message. - Select an existing outbound message to view details about it or view workflow rules and approval processes that use it. - Click **Edit** to make changes to an existing outbound message. - Click **Del** to delete an outbound message. ## Tracking Outbound Message Status To track the status of an outbound message, from Setup, enter `Outbound Messages` in the `Quick Find` box, select **Outbound Messages**, and then click **View Message Delivery Status**. You can perform several tasks on this page. - View the status of your outbound messages, including the total number of attempted deliveries. - View the action that triggered the outbound message by clicking any workflow or approval process action ID. - Click **Retry** to change the **Next Attempt** date to now. This action causes the message delivery to be immediately retried. - Click **Del** to permanently remove the outbound message from the queue. <!-- document id=1d5273407d4dda72136b3ef9d9f666b4ccc5826f023f68bd8e6274c058faa642 url=/developer/current/en-us/platform/salesforce-developer-environment-dotnet-tipsheet/guides/tip-sheets/salesforce-developer-environment-tipsheet/salesforce-developer-environment-dotnet-overview.md --> # Setting Up Your .NET Developer Environment This tipsheet describes how to set up your local environment so that you can start using Salesforce APIs, such as SOAP API or REST API. **note:** If you're setting up a local environment to develop Salesforce applications using Apex and custom Metadata API components, take a look at the [Salesforce Extensions for Visual Studio Code](https://github.com/forcedotcom/salesforcedx-vscode). This tipsheet focuses on tools and configurations you need to set up your local development system. It assumes you already have a working Salesforce organization with the API Enabled permission. API is enabled by default on Developer Edition, Enterprise Edition, Unlimited Edition, and Performance Edition organizations. To create a Developer Edition org, go to [developer.salesforce.com/signup](https://developer.salesforce.com/signup) and follow the instructions for signing up for a Developer Edition organization. If you have a Salesforce organization you can use for development but need to set up a sandbox for development and testing, see [Deploy Enhancements from Sandboxes](https://help.salesforce.com/articleView?id=deploy_sandboxes_parent.htm) in Salesforce Help. - **[Installing Microsoft Visual Studio](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-visualstudio.md)** You’ll need to install Microsoft Visual Studio to use Salesforce APIs. Visual Studio is a development environment that enables you to create robust .NET applications. - **[Picking a Path Based on Which API You Use](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-dotnet-roadmap.md)** The next steps for setting up your development environment depend on which Salesforce API you want to use. - **[Download Developer WSDL Files (WSDL-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-download-wsdl.md)** Salesforce Web Services Definition Language (WSDL) files provide API details that you use in your developer environment to make API calls. - **[Verify the WSDL Environment (WSDL-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-verify-dotnet-wsdl.md)** You can verify your developer environment with a simple C\# test application in Visual Studio. - **[Setting Up External Client App Access (REST-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-remoteaccess.md)** Because Salesforce REST APIs use OAuth authentication, create an external client app to integrate your application with Salesforce. - **[Verify the REST Environment (REST-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-dotnet-tipsheet/guide/salesforce-developer-environment-verify-dotnet-rest.md)** You can verify your developer environment with a simple C\# test application in Visual Studio. <!-- document id=693ebc3710ce7cb6c17fd5f23f60895e4938f9fe4eac39e68ccb6391354f1e87 url=/developer/current/en-us/platform/salesforce-developer-environment-dotnet-tipsheet/guides/salesforce-developer-environment-dotnet-tipsheet-pdf-archive.md --> # Setting Up Your .NET Developer Environment Previous PDF Versions | API Version | Release | PDF | | ----------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ | | 68.0 | Winter '27 | [Download PDF](https://resources.docs.salesforce.com/264/latest/en-us/sfdc/pdf/salesforce_developer_environment_dotnet_tipsheet.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_developer_environment_dotnet_tipsheet.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/salesforce_developer_environment_dotnet_tipsheet.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/salesforce_developer_environment_dotnet_tipsheet.pdf) | <!-- document id=f4af89b47f63df72e22bc3581ac1cf32f60b55cb65596816f7dbac72950f37f1 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/mobile/pages-mobile-platform-dev-process-system.md --> # Setting Up Your Development System Salesforce provides several different tools and ways to write, edit, and view your code. ## Choosing Your Editor First set up the tool you’ll use to write code. The Developer Console, the Salesforce Extensions for Visual Studio Code, and the Setup editor all work when developing for the Salesforce app, Lightning Experience, and Salesforce Classic. The only exception is the Visualforce Development Mode footer, which is available in Salesforce Classic only. ## Viewing Your Visualforce Page In Salesforce Classic, you can view your page using the https://_yourInstance_.salesforce.com/apex/PageName URL pattern. This method doesn’t work for viewing Salesforce app pages in Lightning Experience, because pages you view using direct URL access always display in Salesforce Classic. To view your page in Lightning Experience, go to https://_yourInstance_.salesforce.com/lightning. The simplest way to get to a specific Visualforce page is to create a tab for it, and then navigate to that tab via the All Items section in the App Launcher. For a more long-term approach, create an “In Development” app, and add and remove your Visualforce tabs to it as you work. 1. From Setup, enter `Apps` in the **Quick Find** box, then select **App Manager**. 2. Click **New Lightning App**, and then create a custom app for your pages in development. **note:** Consider restricting your app to only System Administrators, or a profile you’ve created for developers in your organization. 3. From Setup, enter `App Menu` in the **Quick Find** box, then select **App Menu**. 4. Make sure your In Development app is set to **Visible** in App Launcher. 5. From Setup, enter `Tabs` in the **Quick Find** box, then select **Tabs**. 6. Click **New** in the Visualforce Tabs section, and then create a custom tab for the page currently in development. Make the tab visible only to your development user profile, and add the tab only to your In Development app. 7. Repeat the previous step for each page you want to add to your In Development app. You can also add the following bookmarklet to your browser’s menu or toolbar to navigate directly to your page. This JavaScript fires the Lightning Experience `navigateToURL` event, and is the equivalent of entering in the classic /apex/PageName URL. ```visualforce javascript:(function(){ var pageName = prompt('Visualforce page name:'); $A.get("e.force:navigateToURL").setParams( {"url": "/apex/" + pageName}).fire();})(); ``` <!-- document id=3399704dd050c50e297f50b4e789090c9462c4ed99a519a677a69a46185e1c44 url=/developer/current/en-us/platform/salesforce-developer-environment-tipsheet/guides/tip-sheets/salesforce-developer-environment-tipsheet/salesforce-developer-environment-overview.md --> # Setting Up Your Java Developer Environment This tipsheet describes how to set up your local environment so that you can start using Salesforce APIs, such as SOAP API or REST API. **note:** If you're setting up a local environment to develop Salesforce applications using Apex and custom Metadata API components, take a look at the [Salesforce Extensions for Visual Studio Code](https://github.com/forcedotcom/salesforcedx-vscode). This tipsheet focuses on tools and configurations you need to set up your local development system. It assumes you already have a working Salesforce organization with the API Enabled permission. API is enabled by default on Developer Edition, Enterprise Edition, Unlimited Edition, and Performance Edition organizations. To create a Developer Edition org, go to [developer.salesforce.com/signup](https://developer.salesforce.com/signup) and follow the instructions for signing up for a Developer Edition organization. If you have a Salesforce organization you can use for development but need to set up a sandbox for development and testing, see [Deploy Enhancements from Sandboxes](https://help.salesforce.com/articleView?id=deploy_sandboxes_parent.htm) in Salesforce Help. - **[Installing Java](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-java.md)** You need the Java Developer Kit (JDK) version 8.0 or later to use Salesforce APIs. Java is a robust, cross-platform, widely used language that integrates well with Salesforce. - **[Installing Eclipse](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-eclipse.md)** Eclipse is an integrated development environment (IDE) for Java development. - **[Picking a Path Based on Which API You Use](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-roadmap.md)** The next steps for setting up your development environment depend on which Salesforce API you want to use. - **[Install the Web Services Connector (WSDL-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-wsc.md)** The Lightning Platform Web Services Connector (WSC) is a high-performance runtime framework that makes using WSDL-based Salesforce APIs easier. To install the WSC, download the prebuilt .jar file from the Force MVN repository. - **[Download Developer WSDL Files (WSDL-Based APIs)](https://developer.salesforce.com/salesforce-developer-environment-dotnet-tipsheet/guides/tip-sheets/salesforce-developer-environment-tipsheet/salesforce-developer-environment-download-wsdl.md)** Salesforce Web Services Definition Language (WSDL) files provide API details that you use in your developer environment to make API calls. - **[Generating Java Stub Files (WSDL-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-java-stubs.md)** To use WSDL-based Salesforce APIs with Java, you need to generate .jar stub files that you can use in your Java projects. - **[Verify the WSDL Environment (WSDL-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-verify-wsdl.md)** You can verify your developer environment with a simple Java test application in Eclipse. - **[Installing HttpClient and JSON Frameworks (REST-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-httpclient.md)** To access REST resources, you’ll need to install HttpClient and JSON frameworks. HttpClient lets you access HTTP resources. The JSON framework lets you generate and parse JSON request and response data. - **[Setting Up External Client App Access (REST-Based APIs)](https://developer.salesforce.com/salesforce-developer-environment-dotnet-tipsheet/guides/tip-sheets/salesforce-developer-environment-tipsheet/salesforce-developer-environment-remoteaccess.md)** Because Salesforce REST APIs use OAuth authentication, create an external client app to integrate your application with Salesforce. - **[Verify the REST Environment (REST-Based APIs)](https://developer.salesforce.com/docs/platform/salesforce-developer-environment-tipsheet/guide/salesforce-developer-environment-verify-rest.md)** You can verify your developer environment with a simple Java test application in Eclipse. <!-- document id=0dabf2b46852a8e0c1d2d2c6adc495db8c8a380b74796826028a04d3d9bb7996 url=/developer/current/en-us/platform/salesforce-developer-environment-tipsheet/guides/salesforce-developer-environment-tipsheet-pdf-archive.md --> # Setting Up Your Java Developer Environment Previous PDF Versions | API Version | Release | PDF | | ----------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------- | | 68.0 | Winter '27 | [Download PDF](https://resources.docs.salesforce.com/264/latest/en-us/sfdc/pdf/salesforce_developer_environment_tipsheet.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_developer_environment_tipsheet.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/salesforce_developer_environment_tipsheet.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/salesforce_developer_environment_tipsheet.pdf) | <!-- document id=6baa895d5e268f25695ff7b8bcea0847ed192bf02d014b5b87f6a94ba51ad920 url=/developer/current/en-us/platform/api-asynch/guides/api-asynch/headers/async-api-headers-sforce-call-options.md --> # Sforce Call Options Header Use the Sforce Call Options header to specify client-specific options when accessing Bulk API resources. ## Header Field Name and Values **Field name:** `Sforce-Call-Options` **Field values:** - `client`—A string that identifies a client, for use, for example, in event log files. For an example of using `Sforce-Call-Options`, see [Call Options Header](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_calloptions.htm) in the *REST API Developer Guide*. <!-- document id=c9a99a972a89879b06929e01987532de25fca2f45d54d037e882b2c3f719be59 url=/developer/current/en-us/platform/api-asynch/guides/api-bulk-v2/reference/bulk-api-2-0-headers-sforce-call-options.md --> # Sforce Call Options Header Use the `Sforce-Call-Options` header to specify client-specific options when accessing Bulk API 2.0 resources. ## Header Field Name and Values **Field name:** `Sforce-Call-Options` **Field values:** - `client`—A string that identifies a client, for use, for example, in event log files. - `defaultNamespace`—A string that identifies a developer namespace prefix. Resolve field names in managed packages without having to specify the namespace everywhere. **Example:** If the developer namespace prefix is `battle`, and you have a custom field called `botId` in a package, set the default namespace with the call options header: ```nolang Sforce-Call-Options: client=CaseSensitiveToken, defaultNamespace=battle ``` Then queries such as the following succeed: ```nolang /services/data/vXX.X/query/?q=SELECT+Id+botID__c+FROM+Account ``` In this case, the actual field queried is the `battle__botId__c` field. Using this header allows you to write client code without having to specify the namespace prefix. In the previous example, without the header you must write `battle__botId__c`. If this field is set, and the query also specifies the namespace, the response doesn’t include the prefix. For example, if you set this header to `battle`, and issue a query like `SELECT+Id+battle__botID__c+FROM+Account`, the response uses a `botId__c` element, not a `battle_botId__c` element. The `defaultNamespace` field is ignored when retrieving describe information, which avoids ambiguity between namespace prefixes and customer fields of the same name. <!-- document id=0b9a14954b0f1a7ac4316b0c8813123cd84ab0f3ee41e11d3f724b926f048a69 url=/developer/current/en-us/platform/change-data-capture/guides/change-data-capture/cdc-standard-objects-task-event-shared.md --> # Shared Activities and Parent Records for Tasks and Events If Shared Activities is enabled, the relationships between a task and its parent records (for example, contacts and lead), which correspond to TaskRelation objects, are tracked through change events. Similarly, the relationships between a calendar event and its parent records, which correspond to EventRelation objects, are tracked. You can receive change events for task relationships on the `/data/TaskRelationChangeEvent` channel, and for event relationships on the `/data/EventRelationChangeEvent` channel. When Shared Activities is not enabled, EventRelation objects associate a calendar event with invitees only. **See Also** - [*Salesforce Help*: Enable Shared Activities](https://help.salesforce.com/articleView?id=activities_enable_shared_activities.htm&type=5) - [*Object Reference for Salesforce and Force.com*: EventRelation](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_eventattendee.htm) - [*Object Reference for Salesforce and Force.com*: TaskRelation](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_taskrelation.htm) <!-- document id=e08e6f5b5bc0006f85dff8479f472eaa2ffdf2da9e3f52ee8690b62a1797faa4 url=/developer/current/en-us/platform/aura-platform/guides/aura/security/security-share-code.md --> # Sharing JavaScript Code Across Components You can build simple Lightning components that are entirely self-contained. However, if you build more complex applications, you probably want to share code, or even client-side data, between components. The `<ltng:require>` tag enables you to load external JavaScript libraries after you upload them as static resources. You can also use `<ltng:require>` to import your own JavaScript libraries of utility methods. Let’s look at a simple counter library that provides a `getValue()` method, which returns the current value of the counter, and an `increment()` method, which increments the value of that counter. ## Create the JavaScript Library 1. In the Developer Console, click **File** | **New** | **Static Resource**. 2. Enter `counter` in the `Name` field. 3. Select `text/javascript` in the `MIME Type` field. 4. Click **Submit**. 5. Enter this code and click **File** | **Save**. ```javascript window._counter = (function() { var value = 0; // private return { //public API increment: function() { value = value + 1; return value; }, getValue: function() { return value; } }; }()); ``` This code uses the JavaScript module pattern. Using this closure-based pattern, the `value` variable remains private to your library. Components using the library can’t access `value` directly. The most important line of the code to note is: ```javascript window._counter = (function() { ``` You must attach `_counter` to the `window` object as a requirement of JavaScript strict mode, which is implicitly enabled in Lightning Locker. Even though `window._counter` looks like a global declaration, `_counter` is attached to the Lightning Locker secure window object and therefore is a namespace variable, not a global variable. If you use `_counter` instead of `window._counter`, `_counter` isn’t available. When you try to access it, you get an error similar to: ```nolang Action failed: ... [_counter is not defined] ``` ## Use the JavaScript Library Let’s use the library in a `MyCounter` component that has a simple UI to exercise the `counter` methods. ```nolang <!--c:MyCounter--> <aura:component access="global"> <ltng:require scripts="{!$Resource.counter}" afterScriptsLoaded="{!c.getValue}"/> <aura:attribute name="value" type="Integer"/> <h1>MyCounter</h1> <p>{!v.value}</p> <lightning:button label="Get Value" onclick="{!c.getValue}"/> <lightning:button label="Increment" onclick="{!c.increment}"/> </aura:component> ``` The `<ltng:require>` tag loads the counter library and calls the `getValue` action in the component’s client-side controller after the library is loaded. Here’s the client-side controller. ```javascript /* MyCounterController.js */ ({ getValue : function(component, event, helper) { component.set("v.value", _counter.getValue()); }, increment : function(component, event, helper) { component.set("v.value", _counter.increment()); } }) ``` You can access properties of the `window` object without having to type the `window.` prefix. Therefore, you can use `_counter.getValue()` as shorthand for `window._counter.getValue()`. Click the buttons to get the value or increment it. Our counter library shares the counter value between any components that use the library. If you need each component to have a separate counter, you could modify the counter implementation. To see the per-component code and for more details, see this blog post about [Modularizing Code in Lightning Components](https://developer.salesforce.com/blogs/developer-relations/2016/12/lightning-components-code-sharing.html). **See Also** - [Using External JavaScript Libraries](https://developer.salesforce.com/docs/platform/aura-platform/js/js-libs-platform.md) - [*Security for Lightning Components:* JavaScript Strict Mode Enforcement](https://developer.salesforce.com/docs/platform/lightning-components-security/guide/js-strict-mode-intro.html) <!-- document id=197bb2b358ce69663589a914d8245ecf34dd5e232c2ab0a89feb1e3064c7b9f0 url=/developer/current/en-us/platform/aura-platform/guides/aura/js/js-helper.md --> # Sharing JavaScript Code in a Component Bundle Put functions that you want to reuse in the component’s helper. Helper functions also enable specialization of tasks, such as processing data and queueing server-side actions. Helper functions are local to a component, improve code reuse, and move the heavy lifting of JavaScript logic away from the client-side controller, where possible. A helper function can be called from any JavaScript code in a component’s bundle, such as from a client-side controller or renderer. Helper functions are similar to client-side controller functions in shape, surrounded by parentheses and curly braces to denote a JavaScript object in object-literal notation containing a map of name-value pairs. A helper function can pass in any arguments required by the function, such as the component it belongs to, a callback, or any other objects. ```javascript ({ helperMethod1: function () { // logic here }, helperMethod2: function (component) { // logic here this.helperMethod3(var1, var2); }, helperMethod3: function (var1, var2) { // do something with var1 and var2 here }, }); ``` To call another function in the same helper, use the syntax: `this.methodName`, where `this` is a reference to the helper itself. For example, `helperMethod2` calls `helperMethod3` with this code. ```javascript this.helperMethod3(var1, var2); ``` ## Creating a Helper A helper resource is part of the component bundle and is auto-wired via the naming convention `{componentName}_Helper.js`. To create a helper using the Developer Console, click **HELPER** in the sidebar of the component. This helper file is valid for the scope of the component to which it’s auto-wired. ## Using a Helper in a Controller Add a `helper` argument to a controller function to enable the function to use the helper. Specify `(component, event, helper)` in the controller. These are standard parameters and you don't have to access them in the function. This controller code calls an `updateItem` helper function. <!-- otherprops: set_clipboard --> ```javascript /* controller */ ({ newItemEvent: function (component, event, helper) { helper.updateItem(component, event.getParam("item")); }, }); ``` Here’s the helper that contains the `updateItem` function called by the controller. <!-- otherprops: set_clipboard --> ```javascript /* helper */ ({ updateItem: function (component, item, callback) { // Update the items via a server-side action var action = component.get("c.saveItem"); action.setParams({ item: item }); // Set any optional callback and enqueue the action if (callback) { action.setCallback(this, callback); } $A.enqueueAction(action); }, }); ``` The `updateItem` function accepts three parameters. 1. `component`—The component to which the helper belongs. 2. `item`—An item that’s set as an `item` parameter for the `saveItem` Apex action. 3. `callback`—An optional callback to call after the `saveItem` Apex action returns. In our example, the `newItemEvent` controller method passes in only two arguments so there’s no callback. ## Using a Helper in a Renderer Add a helper argument to a renderer function to enable the function to use the helper. In the renderer, specify `(component, helper)` as parameters in a function signature to enable the function to access the component's helper. These are standard parameters and you don't have to access them in the function. The following code shows an example on how you can override the `afterRender()` function in the renderer and call `open` in the helper method. ### detailsRenderer.js <!-- otherprops: set_clipboard --> ```javascript ({ afterRender: function (component, helper) { helper.open(component, null, "new"); }, }); ``` ### detailsHelper.js <!-- otherprops: set_clipboard --> ```javascript ({ open: function (component, note, mode, sort) { if (mode === "new") { //do something } // do something else, such as firing an event }, }); ``` **See Also** - [Create a Custom Renderer](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-renderers.md) - [Component Bundles](https://developer.salesforce.com/docs/platform/aura-platform/components/components-bundle.md) - [Handling Events with Client-Side Controllers](https://developer.salesforce.com/docs/platform/aura-platform/guide/js-client-side-controller.md) <!-- document id=7195ae8e6510eee367466b27dcccedb80c5fc12c175df88ef831f670870fd541 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/salesforce1/developer/dev-best-practices/vf-dev-best-practices-dual-use-pages.md --> # Sharing Visualforce Pages Between Mobile and Desktop Revise Visualforce pages that appear in both the Salesforce mobile app and in the full Salesforce site to support both environments. This includes Visualforce pages used as custom actions and Visualforce pages added to standard page layouts. Visualforce pages that need to work in both environments include: - Pages used as custom actions. Custom actions appear in the action bar in the Salesforce mobile app, and in the publisher menu in the full Salesforce site. - Pages added to normal page layouts, when `Available for Lightning Experience, Experience Builder sites, and the mobile app` is enabled for the page. - Custom Visualforce buttons or links added to normal page layouts. - Standard button overrides with Visualforce pages for the New, Edit, View, Delete, and Clone actions. Overriding standard list and tab controls isn’t supported in the app. Button overrides won’t appear in the app unless `Available for Lightning Experience, Experience Builder sites, and the mobile app` is enabled for the page. **note:** Standard buttons that are overridden with a Visualforce page disappear from record detail pages and record lists in the app if `Available for Lightning Experience, Experience Builder sites, and the mobile app` isn’t selected for the Visualforce page that overrides the corresponding button. **note:** Visualforce pages and custom iframes aren’t supported in Lightning Experience on iPad Safari. <!-- document id=2f3ae99d917b987579c9e0f5fd09964314bb0a4ff4af7c4270494596638496f8 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/using/canvas-app-signed-req-authentication.md --> # Signed Request Authentication Signed request is the default authorization method for Canvas apps. The signed request authorization flow varies depending on whether the administrator gives users access to the Canvas app or if users can self-authorize. You can verify signed request information with a client secret, then use signed requests to customize the app and make subsequent calls to Salesforce. **important:** If your Canvas app URL contains a URL fragment identifier (`#`), then the hash mark (`#`) and all characters that follow are stripped from the URL during the authentication flow. To prevent unexpected behavior, avoid using hash marks (`#`) in a Canvas app URL. |Permitted Users Value|Canvas App Accessibility|When the User Must Approve the Canvas App| |---------------------|------------------------|-----------------------------------------| |Admin-approved users are pre-authorized|The app is accessible to users as soon as the administrator installs it in the organization and configures which users can see it. Users don't approve or deny access.|Never| |All users can self-authorize|The app is accessible to all users, but the user is prompted to approve or deny access to the app.|<ul><li>The first time that the user opens the app</li><li>The administrator revokes the access token</li><li>The administrator sets a time limit on the token and that time limit is exceeded</li></ul>| ## POST or GET Behavior: Admin-Approved Users Are Pre-Authorized Salesforce performs a POST to the Canvas app with all the authorization information contained in the body of the signed request, including the refresh token. ## POST or GET Behavior: All Users Can Self-Authorize If the user previously approved the app and access hasn't expired or been revoked, Salesforce performs a POST to the Canvas app with a signed request payload. If the user hasn't approved the app, or if access has expired or been revoked, Salesforce performs a GET to the Canvas app URL. The Canvas app must handle the GET by accepting the call and looking for the URL parameter `_sfdc_canvas_authvalue`. If the Canvas app receives this parameter value, the Canvas app initiates the approve or deny OAuth flow. `_sfdc_canvas_authvalue = user_approval_required` After the OAuth flow is initiated and the user approves the app, the Canvas app calls the `repost()` method with a parameter of _true_ to retrieve the signed request. ## Signed Request Format The signed request is a string of these elements concatenated. - The Canvas app consumer secret encrypted with the HMAC SHA–256 algorithm - A period (`.`) - The context and authorization token JSON encoded in Base64 The signed request looks similar to this string, although it can be longer: `9Rpl6rE7R2bSNjoSfYdERk8nffmgtKQNhr5U/5eSJPI=.eyJjb250ZXh0Ijp7InVzZXIiOnsibGFuZ3V`... Signed request considerations: - Salesforce performs an HTTP POST or GET when invoking the Canvas app URL, depending on the Permitted Users value and whether the refresh token is returned. - Server-side code verifies and decodes the request. - After the app is invoked, you can request a signed request on demand by using the SDK. - **[Canvas App User Flow—Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/user-flow-signed-request.md)** - **[Verifying and Decoding a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-unsigning-code-example.md)** - **[Requesting a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-refresh-signed-request.md)** If your canvas app is set to use signed request for authentication, you can request a signed request on demand by using the SDK. Your app can ask Salesforce to resend the signed request that was used when your app was loaded or to send a new signed request. Requesting a signed request is useful when you are refreshing an expired session or getting authentication information after your app has been redirected. **See Also** - [Authentication](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-authentication.md) - [Verifying and Decoding a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-unsigning-code-example.md) - [Canvas App User Flow—Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/user-flow-signed-request.md) - [Requesting a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-app-refresh-signed-request.md) <!-- document id=c44e289a2eb37ec73f257d0158164d55bbcc55838f97fa3d45e1fff0faca9808 url=/developer/current/en-us/platform/canvas-framework/guides/platform-connect/reference/signed-request-object.md --> # SignedRequest Canvas provides a SignedRequest object that has methods you can use to work with signed requests. |Method|Signature|Description| |------|---------|-----------| |`verifyAndDecode`|`public static CanvasRequest verifyAndDecode(String input, String secret) throws SecurityException`|Used to verify and decode a signed request; returns a [CanvasRequest](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-request-object.md) Java object.| |`verifyAndDecodeAsJson`|`public static String verifyAndDecodeAsJson(String input, String secret) throws SecurityException`|Used to verify and decode a signed request; returns the [CanvasRequest](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-request-object.md) data in a JSON string.| **See Also** - [CanvasRequest](https://developer.salesforce.com/docs/platform/canvas-framework/guide/canvas-request-object.md) - [Verifying and Decoding a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-unsigning-code-example.md) - [Requesting a Signed Request](https://developer.salesforce.com/docs/platform/canvas-framework/using/canvas-app-refresh-signed-request.md) <!-- document id=6fc78c53a8f7eaee494772a5d451637cc4476160f7d663a5808ab5652d3d4625 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-email-simple.md --> # Simple Email Actions Send an email where you specify the subject, body, and recipients. Available in API version 32.0 and later. **Email Sending Limits** If you're using `logEmailOnSend` or `emailTemplateId`, the daily email-sending limit is based on the single email limit. See [General Email Limits](https://help.salesforce.com/s/articleView?id=000381534&type=1). If you're not using `logEmailOnSend` or `emailTemplateId`, the daily email-sending limit is based on the daily workflow email limit. See [Proactive Alert Monitoring: Daily Workflow Email Limit](https://help.salesforce.com/s/articleView?id=000382442&type=1). ## Supported REST HTTP Methods **URI:** Get a list of available simple email actions: `/services/data/vXX.X/actions/standard/emailSimple` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs **Configure Recipient Details** |Input|Type|Description| |-----|----|-----------| |`bccAddresses`|text|Optional. A comma-delimited list or a collection of recipient email addresses to send a copy of the email to. BCC recipients are hidden from other recipients. This parameter accepts single-value resources and collection variables of type string. The maximum size for this field is 4,000 bytes. This field is available in API version 65.0 and later. If `recipientAddresses`, `ccAddresses`, `bccAddresses`, and `recipientId` are also used, the combined number of recipients must be 150 or fewer.| |`ccAddresses`|text|Optional. A comma-delimited list or a collection of recipient email addresses to send a copy of the email to. CC recipients are visible to all recipients. This parameter accepts single-value resources and collection variables of type string. The maximum size for this field is 4,000 bytes. This field is available in API version 65.0 and later. If `recipientAddresses`, `ccAddresses`, `bccAddresses`, and `recipientId` are also used, the combined number of recipients must be 150 or fewer.| |`recipientAddresses`|string|Optional. A comma-delimited list or a collection of the recipients' email addresses. This parameter accepts single-value resources and collection variables of type string. The maximum size for this field is 4,000 bytes. This field is available in API version 65.0 and later. If `recipientAddresses`, `ccAddresses`, `bccAddresses`, and `recipientId` are also used, the combined number of recipients must be 150 or fewer.| **Configure Sender Details** |Input|Type|Description| |-----|----|-----------| |`senderAddress`|string|Optional. The organization-wide email address to be used as the sender. Required only if `senderType` is set to `OrgWideEmailAddress`. If a scheduled flow sets `senderType` to `OrgWideEmailAddress`, then `senderAddress` is required.| |`senderType`|string|Optional. Email address used as the email's From and Reply-To addresses. Valid values are: `CurrentUser` (email address of the user running the flow; default), `DefaultWorkflowUser` (email address of the default workflow user), or `OrgWideEmailAddress` (the org-wide email address specified in `senderAddress`). In scheduled flows, the only valid value is `OrgWideEmailAddress`.| **Configure Email Content** To configure the email content in your email flow, use the following input parameters. You can create your email content or use an existing email template. |Input|Type|Description| |-----|----|-----------| |`addThreadingTokenToBody`|boolean|Optional. Indicates whether to create a unique token for the related record and add it to the email body. When the related record is a case record, Email-to-Case uses the token to link future email responses to that case. To link future email responses to other records, create an Apex Email Service and use the `EmailMessages.getRecordIdFromEmail` function to find the record that matches the token.| |`addThreadingTokenToSubject`|boolean|Optional. Indicates whether to create a unique token for the related record and add it to the email subject. When the related record is a case record, Email-to-Case uses the token to link future email responses to that case. To link future email responses to other records, create an Apex Email Service and use the `EmailMessages.getRecordIdFromEmail` function to find the record that matches the token.| |`attachmentId`|string|Optional. A comma-delimited list of attachment IDs in the email. This parameter accepts single-value resources of the string type that contain a list of attachments. The value is treated as text. This field is available in API version 63.0 and later. The attachment ID can be of a Document, Content Version, or Attachment item.| |`attachmentIdCollection`|string|Optional. A collection of attachment IDs to include in the email. This parameter accepts collection variables of type text. This field is available in API version 64.0 and later. The attachment ID can be of a Document, Content Version, or Attachment item.| |`emailBody`|textarea|The body of the email. Required for flows using Send Email Action version 1.0.1 and `composeEmailContent` option. Hidden for flows using Send Email Action version 1.0.1 and `useEmailTemplate` selected.| |`emailSubject`|string|The subject of the email. Required for flows using Send Email Action version 1.0.1 and `composeEmailContent` option. Hidden for flows using Send Email Action version 1.0.1 and `useEmailTemplate` selected.| |`emailTemplateId`|text|The ID of the email template to use for the subject and body of the email. Required for flows using Send Email Action version 1.0.1 and `useEmailTemplate` option. Optional for flows using Send Email Action version 1.0.0. Hidden for flows using Send Email Action version 1.0.1 and `composeEmailContent` selected. If this input is included, `recipientId` is required. If the email template has merge fields from an object other than the one associated with `recipientId`, specify the record used to supply those merge fields in `relatedRecordId`. This field is available in API version 58.0 and later. If this input is specified, it changes the API called by the action, which can impact your daily email-sending limit. See [Flow Core Action: Send Email](https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_sendemail.htm) in Salesforce Help.| |`logEmailOnSend`|boolean|Optional. Indicates whether to log the email on the specified records' activity time lines. Valid values are `true` and `false`. Default value is `false`, and the email isn't logged. To log an email, you must specify a value in `recipientId` or `relatedRecordId`. This field is available in API version 58.0 and later. If this input is set to `true`, it changes the API called by the action, which can impact your daily email-sending limit. See [Flow Core Action: Send Email](https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_sendemail.htm) in Salesforce Help.| |`recipientId`|text|Optional. The ID of a lead or a contact record. If `logEmailOnSend` is included, then `recipientId` is the ID of the person to send and log the email to. If `emailTemplateId` is included, then `recipientId` is required and is the ID of the person to send the email to. The maximum size for this field is 4,000 bytes. This field is available in API version 58.0 and later. If `recipientAddresses`, `ccAddresses`, `bccAddresses`, and `recipientId` are also used, the combined number of recipients must be 150 or fewer.| |`relatedRecordId`|text|Optional. The ID of a record that's not a person, for example the ID of a case record. If `logEmailOnSend` is included, `relatedRecordId` is the ID of a secondary record to log the email to. In this case, `relatedRecordId` can't be used to log an email if `recipientId` is a lead record. This field is available in API version 58.0 and later. If `emailTemplateId` is included, `relatedRecordId` is the ID of the non-recipient record used to populate email template merge fields.| |`sendRichBody`|boolean|Optional. Indicates whether you want the resource specified for the **Body** parameter to use rich text. Valid values are `true` and `false`. The default value is `false`. Hidden for flows using Send Email Action version 1.0.1 and `useEmailTemplate` selected.| |`useLineBreaks`|boolean|Optional. Indicates whether to render the line breaks in the rich-text-formatted body text template. Valid values are `true` and `false`. The default value is `false`. Hidden for flows using Send Email Action version 1.0.1 and `useEmailTemplate` selected.| ## Outputs None. <!-- document id=275fe4887aad00680c32d127bdf7b2cd13b0ca406f130e063edd0c08b3d06243 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/components/pages-compref-site-googleanalyticstracking.md --> # site:googleAnalyticsTracking The standard component used to integrate Google Analytics with Force.com sites to track and analyze site usage. Add this component just once, either on the site template for the pages you want to track, or the individual pages themselves. Don't set the component for both the template and the page. Attention: This component only works on pages used in a Force.com site. Sites must be enabled for your organization and the Analytics Tracking Code field must be populated. To get a tracking code, go to the Google Analytics website. ## Example ```apex <!-- Google Analytics recommends adding the component at the bottom of the page to avoid increasing page load time. --> <site:googleAnalyticsTracking/> ``` The example above renders the following HTML: ```html <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script> try { var pageTracker = _gat._getTracker("{!$Site.AnalyticsTrackingCode}"); if ({!isCustomWebAddressNull}) { pageTracker._setCookiePath("{!$Site.Prefix}/"); } else if ({!isCustomWebAddress}) { pageTracker._setAllowLinker(true); pageTracker._setAllowHash(false); } else { pageTracker._setDomainName("none"); pageTracker._setAllowLinker(true); pageTracker._setAllowHash(false); } pageTracker._trackPageview(); } catch(err) { } </script> ``` ## Attributes |Attribute Name|Attribute Type|Description|Required?|API Version|Access| |--------------|--------------|-----------|---------|-----------|------| |`id`|String|An identifier that allows the component to be referenced by other components in the page.| |14.0|global| |`rendered`|Boolean|A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.| |14.0|global| <!-- document id=36a212c98c9915c8a1e670817a9fa894b062e789aa384e2041c24a1e5928cc41 url=/developer/current/en-us/platform/salesforce-pages-developers-guide/guides/pages/components/pages-compref-site-previewasadmin.md --> # site:previewAsAdmin This component shows detailed error messages on a site in administrator preview mode. We recommend that you add it right before the closing apex:page tag. Note: The site:previewAsAdmin component contains the apex:messages tag, so if you have that tag elsewhere on your error pages, you will see the error message twice. ## Example ```apex <!-- We recommend adding this component right before your closing apex:page tag. --> <site:previewAsAdmin/> ``` The example above renders the following HTML: ```html <span id="j_id0:j_id50"> <span id="j_id0:j_id50:j_id51:j_id52"> <div style="border-color:#FF9900; border-style:solid; border-width:1px; padding:5px 0px 5px 6px; background-color:#FFFFCC; font-size:10pt; margin-right:210px; margin-left:210px; margin-top:25px;"> <table cellpadding="0" cellspacing="0"> <tbody><tr> <td><img src="/img/sites/warning.png" height="40" style="padding:5px;margin:0px;" width="40" /></td> <td> <strong><ul id="j_id0:j_id50:j_id51:msgs3" style="margin:5px;"><li>Page not found:test </li></ul> </strong> <a href="/sites/servlet.SiteDebugMode?logout=1" style="padding:40px;margin:15px;">Logout of Administrator Preview Mode</a> </td> </tr> </tbody> </table> </div> </span> </span> ``` ## Attributes |Attribute Name|Attribute Type|Description|Required?|API Version|Access| |--------------|--------------|-----------|---------|-----------|------| |`id`|String|An identifier that allows the component to be referenced by other components in the page.| |14.0|global| |`rendered`|Boolean|A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.| |14.0|global| <!-- document id=d9ce1d015187623210a104378cc8dbc1c6132a3e0180e2b956f75d01040f30d9 url=/developer/current/en-us/platform/api-rest/guides/resources/request-body-ls-skillrequirement.md --> # Skill Requirement List of skills that are required to complete a particular task for a work type. <!-- document id=d0cb433f68aa7c1bf8cb2900f620843d073229f3a7d4245dc240993cc85fd146 url=/developer/current/en-us/platform/salesforce-large-data-volumes-bp/guides/cce/ldv-deployments/ldv-deployments-infrastructure-skinny-tables.md --> # Skinny Tables Salesforce can create skinny tables to contain frequently used fields and to avoid joins. This can improve the performance of certain read-only operations. Skinny tables are kept in sync with their source tables when the source tables are modified. If you want to use skinny tables, contact Salesforce Customer Support. When enabled, skinny tables are created and used automatically where appropriate. You can’t create, access, or modify skinny tables yourself. If the report, list view, or query you’re optimizing changes—for example, to add new fields—you’ll need to contact Salesforce to update your skinny table definition. ## How Skinny Tables Can Improve Performance For each object table that’s visible to you, Salesforce maintains other, separate tables at the database level for standard and custom fields. This separation, which is invisible to customers, ordinarily requires a join when a query contains both kinds of fields. A skinny table contains both kinds of fields and also omits soft-deleted records. This table shows an Account view, a corresponding database table, and a skinny table that can speed up Account queries. ![Skinny Table to Speed up Account Queries](https://developer.salesforce.com/media/salesforce-large-data-volumes-bp/ldv_deployments_skinny_table.png) Read-only operations that reference only fields in a skinny table don’t require an extra join, and can consequently perform better. Skinny tables are most useful with tables containing millions of records to improve the performance of read-only operations, such as reports. **important:** Skinny tables aren’t a magic wand to wave at performance problems. There’s overhead in maintaining separate tables that hold copies of live data. Using them in an inappropriate context can lead to performance degradation instead of improvement. Skinny tables can be created on custom objects, and on Account, Contact, Opportunity, Lead, and Case objects. They can enhance performance for reports, list views, and SOQL. Skinny tables can contain the following types of fields. - Checkbox - Currency - Date - Date and time - Email - Number - Percent - Phone - Picklist (multi-select) - Text - Text area - Text area (long) - URL Skinny tables and skinny indexes can also contain encrypted data. Here is an example of how a skinny table can speed up queries. Instead of using a date range like `01/01/11` to `12/31/11`—which entails an expensive, repeated computation to create an annual or year-to-date report—you can use a skinny table to include a `Year` field and to filter on `Year = '2011'`. ## Considerations - Skinny tables can contain a maximum of 200 columns. - Skinny tables can’t contain fields from other objects. - For Full sandboxes: Skinny tables are copied to your Full sandbox orgs. For other types of sandboxes: Skinny tables aren’t copied to your sandbox organizations. To have production skinny tables activated for sandbox types other than Full sandboxes, contact Salesforce Customer Support. <!-- document id=62af49f5a7b47ac9f398bf183f0ffc252d183dd954edfbb8a770b0428d8c0a38 url=/developer/current/en-us/platform/api-action/guides/api-action/objects/actions-obj-slack.md --> # Slack Actions Manage Slack channels, channel members, and messages. ## Supported REST HTTP Methods REST methods aren't currently supported for Slack actions. **URI:** Get a list of available Slack actions: `/services/data/vXX.X/actions/standard/slack_action_name` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Archive Slack Channel Archive a Slack channel. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackArchiveChannel` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackChannelId`|string|Required. Specifies the ID of the Slack channel to execute the action on. It's also known as the Slack conversation ID. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| ## Check Users Are Connected to Slack Determine whether a collection of Salesforce users is connected to a given Slack app. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup. Otherwise, the action fails. Additionally, the user that initiates the flow and any users impacted by the action must have logged in to a Salesforce Slack app at least one time. URI: `/services/data/vXX.X/actions/standard/slackCheckUsersAreConnectedToSlack` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdsToCheck`|string|Required. Specifies the collection resource that contains the Salesforce user IDs to check. The maximum number of user IDs is 1,000.| |Output|Type|Description| |------|----|-----------| |`userIdsConnectedTo Slack`|string|The Salesforce user IDs connected to Slack.| |`userIdsNotConnectedTo Slack`|string|The Salesforce user IDs that aren't connected to Slack.| ## Create a Slack Channel Create a Slack channel. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackCreateChannel` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackChannelName`|string|Required. Specifies the name of the new Slack channel.| |`isChannelPrivate`|boolean|Indicates whether the new channel is private. For more information about channel types, see [https://slack.com/help/articles/360017938993-What-is-a-channel](https://slack.com/help/articles/360017938993-What-is-a-channel). The default value is `false`.| |`slackWorkspaceIdForChannel`|string|Specifies the ID of the workspace that contains the new channel.| |Output|Type|Description| |------|----|-----------| |`slackChannelId`|string|The ID of the new channel.| ## Edit Slack Message Edit a message that was previously sent to Slack. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackUpdateMessage` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The Slack app must be a member of the conversation that contains the message to edit. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackConversationId`|string|Required. Specifies the ID of the channel or direct message to send the message to. Alternatively, specify a Slack user ID if the message was sent to the user via the Messages tab of the Slack app. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`slackMessage`|string|Required. Specifies the message to send. For best results, include no more than 4,000 characters. Slack truncates messages containing more than 40,000 characters. Enter a value or select a resource.| |`slackMessageTimestamp`|string|Required. Specifies the timestamp of the sent message, for example, `1234567890.123456`. The numerals before the period character (.) specify a Unix timestamp. The numerals after the period character specify microseconds. You can store the Slack Message Timestamp output parameter of the Send Slack Message, Edit Slack Message, or Send Message To Launch Flow (Beta) action as a resource to use later.| |`viewApiName`|string|Specifies the API name of the view that the message is sent with.| |`recordId`|string|Specifies the Salesforce record ID to send to the view.| |Output|Type|Description| |------|----|-----------| |`slackMessageTimestamp`|string|The timestamp of the sent message.| ## Get Information About Slack Conversation Retrieve the name of a Slack channel and find out whether it's archived. Archived channels are closed to new activity, but users can still view and search an archived channel's message history. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackGetConversationInfo` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackConversationId`|string|Required. Specifies the ID of the channel to obtain information about. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |Output|Type|Description| |------|----|-----------| |`slackConversationId`|string|The ID of the channel that you retrieved information about.| |`slackConversationName`|string|The name of the channel that you retrieved information about.| |`isConversationArchived`|boolean|Indicates whether the channel is archived.| ## Invite Users to Slack Channel Add users who are connected to a given Slack app to a Slack channel or direct message. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. Additionally, the user that initiates the flow and any users impacted by the action must have logged in to a Salesforce Slack app at least one time. URI: `/services/data/vXX.X/actions/standard/slackInviteUsersToChannel` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackChannelId`|string|Required. Specifies the ID of the Slack channel to execute the action on. It's also known as the Slack conversation ID. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`slackWorkspaceIdForChannel`|string|Specifies the ID of the workspace that contains the channel to invite users to.| |`userIdsToInvite`|string|Required. Specifies the collection resource that contains the Salesforce user IDs of the users to invite.| ## Pin or Unpin Slack Message Pin or unpin a message in a Slack channel or direct message. Pin messages so that they're readily available from the conversation header. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackPinMessage` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The Slack app must be a member of the conversation that contains the message to pin or unpin. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackConversationId`|string|Required. Specifies the ID of the Slack channel to execute the action on. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`slackMessageTimestamp`|string|Required. Specifies the timestamp of the sent message, for example, `1234567890.123456`. The numerals before the period character (.) specify a Unix timestamp. The numerals after the period character specify microseconds.| |`doesPinMessage`|boolean|Required. Indicates whether to pin the message to the conversation header. A value of true pins the message. A value of false unpins the message.| ## Send Slack Message Send a message to a Slack channel or direct message. Available in API version 54.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackPostMessage` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackConversationId`|string|Required. Specifies the ID of the Slack channel to execute the action on. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`slackBotName`|string|Specifies the name of the bot that sends the message in Slack.| |`slackMessage`|string|Required. Specifies the message to send. For best results, include no more than 4,000 characters. Slack truncates messages containing more than 40,000 characters. Enter a value or select a resource.| |`viewApiName`|string|Specifies the API name of the view that the message is sent with.| |`recordId`|string|Specifies the Salesforce record ID to send to the view.| |`slackMessageTimestamp`|string|Required. Specifies the timestamp of the sent message, for example, `1234567890.123456`. The numerals before the period character (.) specify a Unix timestamp. The numerals after the period character specify microseconds. You can store the Slack Message Timestamp output parameter of the Send Slack Message, Edit Slack Message, or Send Message To Launch Flow (Beta) action as a resource to use later.| |Output|Type|Description| |------|----|-----------| |`slackMessageTimestamp`|string|The timestamp of the sent message.| ## Send Slack Message to Launch Flow (Beta) Send a message to a Slack channel or direct message that includes a button from which a recipient can launch a screen flow. Available in API version 55.0. This action is available only if you enable the connection to Slack in Setup and the user who runs the flow is connected to Slack. Otherwise, the action fails. URI: `/services/data/vXX.X/actions/standard/slackSendMessageToLaunchFlow` |Input|Type|Description| |-----|----|-----------| |`slackAppIdForToken`|string|Required. Specifies the ID of the Slack app that executes the action. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackWorkspaceIdForToken`|string|Required. Specifies the ID of the Slack workspace where the Slack app is installed. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token. You can obtain the Slack workspace ID by logging in to Slack.com and launching Slack in your browser. The workspace ID is the penultimate parameter in the URL. For example, in this URL, the workspace ID is `T01234ABCDE`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`userIdForToken`|string|Specifies the Salesforce user ID of the user that the flow uses to connect to Slack. If you don't specify a user ID, the Slack app executes the action. The user or Slack app that executes the action must be a member of the channel. The flow uses the `slackAppIdForToken`, `slackWorkspaceIdForToken`, and `userIdForToken` values to retrieve an access token.| |`slackConversationId`|string|Required. Specifies the ID of the Slack channel to execute the action on. You can obtain the Slack conversation ID by logging in to Slack.com and launching Slack in your browser. The conversation ID is the last parameter in the URL. For example, in this URL, the conversation ID is `C56789FGHIJ`: `https://app.slack.com/client/T01234ABCDE/C56789FGHIJ`.| |`slackBotName`|string|Specifies the name of the bot that sends the message in Slack.| |`slackMessage`|string|Required. Specifies the message to send. For best results, include no more than 4,000 characters. Slack truncates messages containing more than 40,000 characters. Enter a value or select a resource.| |`slackButtonLabel`|string|Required. Specifies the label for the button that appears below the message. The user clicks the button to launch the flow from Slack.| |`slackMessageTimestamp`|string|Required. Specifies the timestamp of the sent message, for example, `1234567890.123456`. The numerals before the period character (.) specify a Unix timestamp. The numerals after the period character specify microseconds. You can store the Slack Message Timestamp output parameter of the Send Slack Message, Edit Slack Message, or Send Message To Launch Flow (Beta) action as a resource to use later.| |Output|Type|Description| |------|----|-----------| |`slackMessageTimestamp`|string|The timestamp of the sent message.| **See Also** - [*Salesforce for Slack Integrations* : Enable Salesforce for Slack Integrations](https://help.salesforce.com/s/articleView?id=slack.slack_apps_enable.htm&type=5) - [*Salesforce Admins*: How Admins Can Connect Salesforce and Slack](https://admin.salesforce.com/blog/2021/how-admins-can-connect-salesforce-and-slack) <!-- document id=6a36c49aa7b51688588b0f3c9b214c065fa18f6374c687a0d13a1192b6cacac8 url=/developer/current/en-us/platform/ajax/guides/ajax/sforce-api-ajax-eol.md --> # SOAP (AJAX) API End-of-Life Policy See which SOAP API versions are supported, unsupported, or unavailable. **note:** The SOAP API `login()` call is scheduled for retirement in Summer ‘27. The `login()` call will be supported in API versions 62.0, 63.0, and 64.0 for a minimum of two years following the release of the version. Salesforce is committed to supporting each API version for a minimum of 3 years from the date of first release. To improve the quality and performance of the API, versions that are over 3 years old sometimes are no longer supported. Salesforce notifies customers who use an API version scheduled for deprecation at least 1 year before support for the version ends. |Salesforce API Versions|Version Support Status|Version Retirement Info| |-----------------------|----------------------|-----------------------| |Versions 31.0 through 68.0|Supported.| | |Versions 21.0 through 30.0|As of Summer ’25, these versions are retired and unavailable.|[Salesforce Platform API Versions 21.0 through 30.0 Retirement](https://help.salesforce.com/s/articleView?id=000389618&type=1)| |Versions 7.0 through 20.0|As of Summer ’22, these versions are retired and unavailable.|[Salesforce Platform API Versions 7.0 through 20.0 Retirement](https://help.salesforce.com/s/articleView?id=000380623&type=1)| If you request any resource or use an operation from a retired API version, SOAP API returns `500:UNSUPPORTED_API_VERSION` error code. To identify requests made from old or unsupported API versions, use the [API Total Usage](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_eventlogfile_apitotalusage.htm) event type. <!-- document id=45234c15d736b7ec1d7173f310aacf91404c925905d0a680b3a6a8127c3116ba url=/developer/current/en-us/platform/salesforce-app-limits-cheatsheet/guides/limits/salesforce-app-limits-platform-apicalls.md --> # SOAP API Call Limits |API Name|API Limit|Limit Description| |--------|---------|-----------------| |`create()`|Maximum number of records created|Your client application can add up to 200 records in a single `create()` call. If a create request exceeds 200 records, then the entire operation fails.| |`describeSObjects()`|Maximum number of objects returned|The `describeSObjects()` call is limited to a maximum of 100 objects returned.| |`getDeleted()`|Limits for returned records|If a `getDeleted()` call returns more than 600,000 records, the exception EXCEEDED_ID_LIMIT is returned.| |`login()`|Login request size limit|The login request size is limited to 10 KB.| |`merge()`|Merge request limits|<ul><li>Up to 200 merge requests can be made in a single SOAP call.</li><li>Up to three records can be merged in a single request, including the master record. This limit is the same as the limit enforced by the Salesforce user interface. To merge more than 3 records, do a successive merge.</li><li>External ID fields can’t be used with `merge()`.</li><li>If you selected the option to retain the most recently updated data privacy record for merging leads and contacts, but the caller doesn’t have CRUD permission for the selected data privacy record, the merge process selects the data privacy record already associated with the master record.</li></ul>| |`update()`|Maximum number of records updated|Your client application can change up to 200 records in a single `update()` call. If an update request exceeds 200 records, the entire operation fails.| |`query()` and `queryMore()`|Batch size limits|The maximum batch size is 2,000 records, but this number is only a suggestion. To maximize performance, the requested batch size isn’t necessarily the actual batch size. Salesforce Web Service Connector (WSC) clients can set the batch size by calling `setQueryOptions()` on the connection object. C# client applications can change the batch size in the `QueryOptions` portion of the SOAP header before invoking the `query()` call. If the SOQL statement selects two or more custom fields of type long text, the batch size can’t be greater than 200 records. This limit prevents large SOAP messages from being returned.| <!-- document id=a8d8bda05e74b7570bfe506a8e1357fa189421108ebf2c499ae3c2457a46e837 url=/developer/current/en-us/platform/api/guides/api-pdf-archive.md --> # SOAP API 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/apex_api.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/apex_api.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/apex_api.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/apex_api.pdf) | <!-- document id=0f1a9e3c5b118eff81d559bf4bd5be2a20f17a1ccd61ac1d5b337f760958d053 url=/developer/current/en-us/platform/api/guides/api/concepts/api-eol-soap.md --> # SOAP API End-of-Life Policy See which SOAP API versions are supported, unsupported, or unavailable. **note:** The SOAP API `login()` call is scheduled for retirement in Summer ‘27. The `login()` call will be supported in API versions 62.0, 63.0, and 64.0 for a minimum of two years following the release of the version. For more information, see [Platform SOAP API login() Retirement](https://help.salesforce.com/s/articleView?id=005132110&type=1). Salesforce is committed to supporting each API version for a minimum of 3 years from the date of first release. To improve the quality and performance of the API, versions that are over 3 years old sometimes are no longer supported. Salesforce notifies customers who use an API version scheduled for deprecation at least 1 year before support for the version ends. <sfdocstbl><table> <col> </col> <col> </col> <col> </col> <thead> <tr> <th> Salesforce API Versions </th> <th> Version Support Status </th> <th> Version Retirement Info </th> </tr> </thead> <tbody> <tr> <td> Versions 41.0 through 66.0 </td> <td> Supported. </td> <td>   </td> </tr> <tr> <td> Versions 31.0 through 40.0 </td> <td> <p> Supported. </p> <p> Deprecated and unsupported from Summer ’27. </p> <p> Retired from Summer ’28. </p> </td> <td> <a href="https://help.salesforce.com/s/articleView?id=005321531&type=1">Salesforce Platform API Versions 31.0 through 40.0 Retirement</a> </td> </tr> <tr> <td> Versions 21.0 through 30.0 </td> <td> As of Summer ’25, these versions are retired and unavailable. </td> <td> <a href="https://help.salesforce.com/s/articleView?id=000389618&type=1">Salesforce Platform API Versions 21.0 through 30.0 Retirement</a> </td> </tr> <tr> <td> Versions 7.0 through 20.0 </td> <td> As of Summer ’22, these versions are retired and unavailable. </td> <td> <a href="https://help.salesforce.com/s/articleView?id=000380623&type=1">Salesforce Platform API Versions 7.0 through 20.0 Retirement</a> </td> </tr> </tbody> </table></sfdocstbl> If you request any resource or use an operation from a retired API version, SOAP API returns `500:UNSUPPORTED_API_VERSION` error code. To identify requests made from old or unsupported API versions, use the [API Total Usage](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_eventlogfile_apitotalusage.htm) event type. <!-- document id=56c64649e12d6a3985bc56f3871dcf8ddf7190263325ef4221692a0cf130ab19 url=/developer/current/en-us/platform/caf-dev/guides/caf/caf-dev-examples-api-soap.md --> # SOAP API Examples Use SOAP API to create, update, or delete a record with Custom Address Fields data. **note:** Before you create a custom address field, review the [Custom Address Fields Requirements and Limitations](https://developer.salesforce.com/docs/platform/caf-dev/guide/caf-dev-limitations.md). To discuss the feature and ask questions, join the [Custom Address Fields Discussion](https://trailhead.salesforce.com/trailblazer-community/groups/0F94S000000H3KISA0) group on the Trailblazer Community. ## Create a New Account with Data in a Custom Address Field This example creates an Account record which includes address data stored in the Mailing Address custom address field. ```xml <?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <urn:SessionHeader> <urn:sessionId>$0XXXXXXXXXXXXXXX</urn:sessionId> </urn:SessionHeader> </soapenv:Header> <soapenv:Body> <urn:create> <urn:sObjects xsi:type="urn1:Account"> <!--Zero or more repetitions:--> <Name>Puneet Ahmedabad Account</Name> <Mailing_Address__City__s>Ahmedabad</Mailing_Address__City__s> <Mailing_Address__Street__s>102 Suryakoti</Mailing_Address__Street__s> <Mailing_Address__PostalCode__s>380022</Mailing_Address__PostalCode__s> <Mailing_Address__StateCode__s>GJ</Mailing_Address__StateCode__s> <Mailing_Address__CountryCode__s>IN</Mailing_Address__CountryCode__s> <Mailing_Address__Latitude__s>37.775</Mailing_Address__Latitude__s> <Mailing_Address__Longitude__s>-122.418</Mailing_Address__Longitude__s> </urn:sObjects> </urn:create> </soapenv:Body> </soapenv:Envelope> ``` ## Update Data Within a Custom Address Field on a Record This example updates the data stored in the Mailing Address custom address field for record ID `001XXXXXXXXXXXXXXX`. ```xml <?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <urn:SessionHeader> <urn:sessionId>$0XXXXXXXXXXXXXXX</urn:sessionId> </urn:SessionHeader> </soapenv:Header> <soapenv:Body> <urn:update> <urn:sObjects xsi:type="urn1:Account"> <Id>$001XXXXXXXXXXXXXXX</Id> <Mailing_Address__Street__s>20 Udhyog Nagar</Mailing_Address__Street__s> <Mailing_Address__City__s>Surendranagar</Mailing_Address__City__s> <Mailing_Address__PostalCode__s>363001</Mailing_Address__PostalCode__s> <Mailing_Address__StateCode__s>GJ</Mailing_Address__StateCode__s> <Mailing_Address__CountryCode__s>IN</Mailing_Address__CountryCode__s> <Mailing_Address__Latitude__s>22.757580</Mailing_Address__Latitude__s> <Mailing_Address__Longitude__s>71.619350</Mailing_Address__Longitude__s> </urn:sObjects> </urn:update> </soapenv:Body> </soapenv:Envelope> ``` ## Delete Data Within a Custom Address Field from a Record To delete address data stored within a custom address field on a record, update the record. This example deletes the address stored in the Mailing Address custom address field on the Account with record with ID `001XXXXXXXXXXXXXXX`. ```xml <?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <urn:SessionHeader> <urn:sessionId>$0XXXXXXXXXXXXXXX</urn:sessionId> </urn:SessionHeader> </soapenv:Header> <soapenv:Body> <urn:update> <urn:sObjects xsi:type="urn1:Account"> <Id>$001XXXXXXXXXXXXXXX</Id> <Name>Acc updated</Name> <urn:fieldsToNull>Mailing_Address__Street__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__City__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__PostalCode__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__StateCode__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__CountryCode__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__Latitude__s</urn:fieldsToNull> <urn:fieldsToNull>Mailing_Address__Longitude__s</urn:fieldsToNull> </urn:sObjects> </urn:update> </soapenv:Body> </soapenv:Envelope> ``` ## Delete a Record That Contains Data in a Custom Address Field This example deletes the Account record with ID `001XXXXXXXXXXXXXXX`. When a record is deleted, all data for that record is deleted, including the custom address field information. ```xml <?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <urn:SessionHeader> <urn:sessionId>$0XXXXXXXXXXXXXXX</urn:sessionId> </urn:SessionHeader> </soapenv:Header> <soapenv:Body> <urn:delete> <Id>$001XXXXXXXXXXXXXXX</Id> </urn:delete> </soapenv:Body> </soapenv:Envelope> ``` <!-- document id=ec0df74ef04052dc2ad195febb0dd7cd04c4d0df60da4521987289f24a25a707 url=/developer/current/en-us/platform/api/guides/api/quickstart/soap-rns.md --> # SOAP API Release Notes Use the Salesforce Release Notes to learn about the most recent updates and changes to SOAP API. For updates and changes that impact the Salesforce Platform, including SOAP API, see the [API Release Notes](https://help.salesforce.com/s/articleView?id=release-notes.rn_api.htm). When there are new or changed features in SOAP API, a link to those specific release notes is included here. Otherwise, refer to the API Release Notes for any recent changes that impact the platform and all APIs. <!-- document id=dcaf321359cd913a9735d1f8600c803e7ac597b43c65c951db0b3c80d72945bc url=/developer/current/en-us/platform/ajax/guides/ajax/sforce-api-ajax-headers.md --> # SOAP Header Options with the AJAX Toolkit All header options in the SOAP API are supported in the toolkit, but they are specified differently than in the API. ## Syntax for Specifying Header Options - For headers that have only one option such as queryOptions: ```javascript sforce.connection.header_option_name="value"; ``` - For headers that have more than one option such as assignmentRuleHeader: ```javascript sforce.connection.header_name = {} sforce.connection.header_name.header_option_name="value"; ``` Here's each valid option, organized by its corresponding SOAP header name in the API for your reference. ## assignmentRuleHeader `assignmentRuleId` — ID of a specific assignment rule to run for the case or lead. Can be an inactive assignment rule. The ID can be retrieved by querying the AssignmentRule object. If specified, do not specify `useDefaultRule`. This element is ignored for accounts, because all territory assignment rules are applied. If the value is not in correct ID format (15-character or 18-character Salesforce ID), the call fails and a `MALFORMED_ID` exception is returned. `useDefaultRule` — If true for a Case or Lead, uses the default (active) assignment rule for a Case or Lead. If specified, do not specify an `assignmentRuleId`. If true for an Account, all territory assignment rules are applied, and if false, no territory assignment rules are applied. ## callOptions `client` — A string that identifies a particular client. `defaultNamespace` — A string that identifies a developer namespace prefix. ## emailHeader `triggerAutoResponseEmail` — Indicates whether to trigger auto-response rules (`true`) or not (`false`), for leads and cases. In the Salesforce user interface, this email can be automatically triggered by a number of events, for example resetting a user password. `triggerOtherEmail` — Indicates whether to trigger email outside the organization (`true`) or not (`false`). In the Salesforce user interface, this email can be automatically triggered by creating, editing, or deleting a contact for a case. `triggerUserEmail` — Indicates whether to trigger email that is sent to users in the organization (`true`) or not (`false`). In the Salesforce user interface, this email can be automatically triggered by a number of events: resetting a password, creating a new user, adding comments to a case, or creating or modifying a task. ## loginScopeHeader `organizationId` — The ID of the organization against which you will authenticate Self-Service users. `portalId` — Specify only if user is a Customer Portal user. The ID of the portal for this organization. The ID is available in the Salesforce user interface: - From Setup, enter `Customer Portal Settings` in the `Quick Find` box, then select **Customer Portal Settings**. - Select a Customer Portal name, and on the Customer Portal detail page, the URL of the Customer Portal displays. The Portal ID is in the URL. ## mruHeader `updateMru` — Indicates whether to update the list of most recently used items (`true`) or not (`false`). For retrieve, if the result has only one row, MRU is updated to the ID of the retrieve result. For query, if the result has only one row and the ID field is selected, the MRU is updated to the ID of the query result. ## queryOptions `batchSize` — Batch size for the number of records returned in a query or queryMore call. Child objects count toward the number of records for the batch size. For example, in relationship queries, multiple child objects may be returned per parent row returned. The default is 500; the minimum is 200, and the maximum is 2,000. ## sessionHeader `sessionId` — Session ID returned by the login call to be used for subsequent call authentication. Since session management is done for you by the AJAX Toolkit, most scripts won't need to use this header option. ## userTerritoryDeleteHeader `transferToUserId` — The ID of the user to whom open opportunities in that user's territory will be assigned when an opportunity's owner (user) is removed from a territory. <!-- document id=5705f656fff2024603b5d0e81e23f89cb4613242978c99d1bcfe85d6343b56fa url=/developer/current/en-us/platform/api/guides/api/header/soap-headers.md --> # SOAP Headers The API provides SOAP headers to client applications. |Header|Description| |------|-----------| |[AllOrNoneHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-allornoneheader.md)|Specifies whether a call rolls back all changes unless all records are processed successfully. This header is available in API version 20.0 and later.| |[AllowFieldTruncationHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-allowfieldtruncation.md)|Specifies the truncation behavior for some field types in API version 15.0 and later.| |[AssignmentRuleHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-assignmentruleheader.md)|Specifies the assignment rule to use when creating or updating an [Account](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_account.htm), [Case](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_case.htm), or [Lead](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_lead.htm).| |[CallOptions](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-calloptions.md)|Specifies the call options for an API request.| |[DebuggingHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-debuggingheader.md)|Returns the debug log in the output header, `DebuggingInfo`, and specifies the level of detail in the debug log.| |[DisableFeedTrackingHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-disablefeedtracking.md)|Specifies whether the changes made in the current call are tracked in feeds.| |[DuplicateRuleHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-duplicateruleheader.md)|Determines options for using duplicate rules to detect duplicate records. Duplicate rules are part of the Duplicate Management feature.| |[EmailHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-emailheader.md)|Sends an email notification when a request is processed. Provides equivalent functionality for the Salesforce user interface.| |[LimitInfoHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-limitinfo.md)|A response header returned from calls to SOAP API. This header returns limit information for the organization. Use this header to monitor your API limits as you make calls against the organization.| |[LocaleOptions](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-localeheader.md)|Specifies the language of the labels returned. The value must be a valid user locale (language and country), such as `de_DE` or `en_GB`. For more information on locales, see the [`Language`](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_categorynodelocalization.htm#languagelocalekey_desc) field on the CategoryNodeLocalization object.| |[LoginScopeHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-loginscopeheader.md)|Specifies the organization ID so that you can authenticate Self-Service users for your organization using the [`login()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login.md) call.| |[MruHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-mruheader.md)|Indicates whether to update the list of most recently used items (`true`) or not (`false`).| |[OwnerChangeOptions](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-ownerchangeoptions.md)|Specifies ownership of attachments and notes.| |[PackageVersionHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-packageversionheader.md)|Specifies the package version for each installed managed package in API version 16.0 and later.| |[QueryOptions](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-queryoptions.md)|Specifies the batch size for query results.| |[SessionHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-sessionheader.md)|Specifies the session ID returned from the login server after a successful [`login()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login.md).| |[UserTerritoryDeleteHeader](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-header-userterritorydeleteheader.md)|Specifies a user to whom open opportunities are assigned when the current owner is removed from a territory.| <!-- document id=d957ba9e28aa2e7d02cce879ad9a8afe7d7a8c02dfe7a482d0ff69d4f4ceb4d0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-approvallayouts.md --> # sObject ApprovalLayouts Retrieve a list of approval layouts for a specified object. This resource is available in REST API version 30.0 and later. - **[Get Approval Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-approvallayouts-get.md)** Gets a list of approval layouts for a specified object. This resource is available in REST API version 30.0 and later. - **[Return Headers for Approval Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-approvallayouts-head.md)** Returns only the headers that are returned by a GET request to sObject ApprovalLayouts resources. This gives you a chance to see header values before retrieving the content of the resource. This resource is available in REST API version 30.0 and later. **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=43b8f0e598efc542e35ddbeac9431ca0ce0031bacd3220ac64ad487d89d5f5ac url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-basic-info.md --> # sObject Basic Information Retrieves basic metadata for a specified object, or creates a new record for the specified object. For example, this resource can be used to retrieve the metadata for the Account object using the GET method, or create a new Account object using the POST method. - **[Get Object Metadata Using sObject Basic Information](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-basic-info-get.md)** Gets basic metadata for a specified object, including some object properties, recent items, and URIs for other resources related to the object. - **[Create Records Using sObject Basic Information](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-basic-info-post.md)** Creates a new record for a specified object based on field values in the request body. <!-- document id=267c7ebf1bbbe6e4dd88ca0e8b2f1ca0db0503b74684277b8de74aa018bccd34 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-blob-retrieve.md --> # sObject Blob Get Gets the specified blob field from an individual record and returns it as binary data. Only certain standard objects have blob fields, such as Attachment, ContentNote, ContentVersion, Document, Folder, and Note. **note:** The sObject Blob Get resource isn’t compatible with Composite API requests, because it returns binary data instead of data in JSON or XML formats. Instead, make individual sObject Blob Get requests to retrieve blob data. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/id/blobField` **Formats:** Binary data **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters:** none required ## Example For an example of retrieving blob data from a Document, see [Get Blob Data](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-blob-retrieve.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=6ad3a5e23d3f378ef6a646e0ef9c36402cc22de9cf28d397ca2698e6f3f19441 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-composite-sobjects-collections.md --> # sObject Collections Executes actions on multiple records in one request. Use sObject Collections to reduce the number of round-trips between the client and server. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire request counts as a single call toward your API limits. This resource is available in API version 42.0 and later. The parameters, request body, and response body of an sObject Collections request depend on the HTTP method. For details, see the specific operation. <!-- document id=0aa29ec84df74983229546f9af2dc86f74e9f9846ef710d0052209d79c97bfa3 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-compactlayouts.md --> # sObject CompactLayouts Retrieve a list of compact layouts for a specific object. This resource is available in REST API version 29.0 and later. - **[Get Compact Layouts Using sObject CompactLayouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-compactlayouts-get.md)** Retrieves a list of compact layouts for a specific object. This resource is available in REST API version 29.0 and later. - **[Return Headers Using sObject CompactLayouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-compactlayouts-head.md)** Returns only the headers that are returned by a GET request to the sObject CompactLayouts resource. This gives you a chance to see header values ahead of time before retrieving the content of the resource. This resource is available in REST API version 29.0 and later. **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=36a3fc2fe0df6fb964ab3f0b827348abb85c3c89a9f77e11697217d83ca8d55f url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-describe.md --> # sObject Describe Completely describes the individual metadata at all levels for the specified object. For example, this can be used to retrieve the fields, URLs, and child relationships for the Account object. For more information about the metadata that is retrieved, see [DescribesObjectResult](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm) in the *SOAP API Developers Guide*. You can use the `If-Modified-Since` or `If-Unmodified-Since` header with this resource. When using the `If-Modified-Since` header, if no available object’s metadata has changed since the provided date, a `304 Not Modified` status code is returned with no response body. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/describe/` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`sObject`|The name of the object. For example, `Account`. A required path parameter.| |`If-Modified-Since`|An optional header specifying a date and time. The request returns records that have been modified after that date and time. The format is `EEE, dd MMM yyyy HH:mm:ss z`. For example: `If-Modified-Since: Mon, 30 Nov 2020 08:34:54 MST`.| |`If-Unmodified-Since`|An optional header specifying a date and time. The request returns records that have not been modified after that date and time. The format is `EEE, dd MMM yyyy HH:mm:ss z`. For example: `If-Unmodified-Since: Mon, 30 Nov 2020 08:34:54 MST`.| ## Example See [Get Field and Other Metadata for an Object](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-describe.md). For an example that uses the `If-Modified-Since` HTTP header, see [Get Object Metadata Changes](https://developer.salesforce.com/docs/platform/api-rest/do-me/sobject-describe-with-ifmodified-header.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) - [Conditional Request Headers](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-rest-conditional-requests.md) <!-- document id=eab881ad1a275100a9beb8094e5b12d42451d86ade7ad515f7ed79450609e693 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-getdeleted.md --> # sObject Get Deleted Retrieves the list of individual records that have been deleted within the given timespan for the specified object. This resource is available in REST API version 29.0 and later. This resource is commonly used in data replication applications. Note the following considerations: - Deleted records are written to a delete log which this resource accesses. A background process that runs every two hours purges records that have been in an organization's delete log for more than two hours if the number of records is above a certain limit. Starting with the oldest records, the process purges delete log entries until the delete log is back below the limit. This is done to protect Salesforce from performance issues related to massive delete logs - Information on deleted records is returned only if the current session user has access to them. - Results are returned for no more than 15 days previous to the day the call is executed (or earlier if an administrator has purged the Recycle Bin). - There is a limit of 600,000 IDs returned from this resource. If more than 600,000 IDs are found, `EXCEEDED_ID_LIMIT` is returned. You can correct the error by choosing start and end dates that are closer together. For information about the Rules and Guidelines, Limits, and Basic Steps for Replicating Deleted Records, see [getDeleted()](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_getdeleted.htm) in the *SOAP API Developer’s Guide*. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/deleted/?start=startDateAndTime&end=endDateAndTime` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`start`|Starting date/time (Coordinated Universal Time (UTC)—not local— timezone) of the timespan for which to retrieve the data. The API ignores the seconds portion of the specified dateTime value (for example, 12:30:15 is interpreted as 12:30:00 UTC). The date and time must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). The date/time value for `start` must chronologically precede `end`. This parameter should be URL-encoded.| |`end`|Ending date/time (Coordinated Universal Time (UTC)—not local— timezone) of the timespan for which to retrieve the data. The API ignores the seconds portion of the specified dateTime value (for example, 12:35:15 is interpreted as 12:35:00 UTC). The date and time must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). This parameter should be URL-encoded| **Response Body** |Property|Type|Description| |--------|----|-----------| |`deletedRecords`|array|Array of deleted records that satisfy the start and end dates specified in the request. Each entry contains the record ID and the date and time the record was deleted in ISO 8601 format, using Coordinated Universal Time (UTC) timezone.| |`earliestDateAvailable`|String|ISO 8601 format timestamp (Coordinated Universal Time (UTC)—not local— timezone) of the last physically deleted object.| |`latestDateCovered`|String|ISO 8601 format timestamp (Coordinated Universal Time (UTC)—not local— time zone) of the last date covered in the request.| ## Example For an example of getting a list of deleted items, see [Get a List of Deleted Records Within a Given Timeframe](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-get-deleted.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=2069e5031b60a25bbb310ad25592e9a4d60429a3cdfd0f450972844f500a34a0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-getupdated.md --> # sObject Get Updated Retrieves the list of individual records that have been updated (added or changed) within the given timespan for the specified object. This resource is available in REST API version 31.0 and later. This resource is commonly used in data replication applications. Note these considerations: - Results are returned for no more than 30 days previous to the day the call is executed. - Your client application can replicate any objects to which it has sufficient permissions. For example, to replicate all data for your organization, your client application must be logged in with “View All Data” access rights to the specified object. Similarly, the objects must be within your sharing rules. - There is a limit of 600,000 IDs returned from this resource. If more than 600,000 IDs are found, `EXCEEDED_ID_LIMIT` is returned. You can correct the error by choosing start and end dates that are closer together. - The call uses the `SystemModstamp` field to determine an object's add or change date. If `SystemModstamp` isn’t available, the call uses `LastModifiedDate`. See “Data Replication” in the [SOAP API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/) for additional details on data replication and data replication limits. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/updated/?start=startDateAndTime&end=endDateAndTime` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`start`|Starting date/time (Coordinated Universal Time (UTC) time zone—not local— timezone) of the timespan for which to retrieve the data. The API ignores the seconds portion of the specified dateTime value (for example, 12:30:15 is interpreted as 12:30:00 UTC). The date and time must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). The date/time value for `start` must chronologically precede `end`. This parameter must be URL-encoded| |`end`|Ending date/time (Coordinated Universal Time (UTC) time zone—not local— timezone) of the timespan for which to retrieve the data. The API ignores the seconds portion of the specified dateTime value (for example, 12:35:15 is interpreted as 12:35:00 UTC). The date and time must be formatted as described in [Valid Date and DateTime Formats](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-valid-date-formats.md). This parameter must be URL-encoded| **Response format** |Property|Type|Description| |--------|----|-----------| |`ids`|array|Array of updated records that satisfy the start and end dates specified in the request. Each entry contains the record ID.| |`latestDateCovered`|String|ISO 8601 format timestamp (Coordinated Universal Time (UTC)—not local— time zone) of the last date covered in the request.| ## Examples For an example of getting a list of updated deleted items, see [Get a List of Updated Records Within a Given Timeframe](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-get-updated.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=4e273ae5ffab9c430f2179f0867439e98d7b88d6774b7344271fb79e13eee957 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts-global.md --> # sObject Global Publisher Layouts Retrieves lists of global publisher layouts. Global publisher layouts customize the actions on global pages (like the Home page). In Lightning Experience, these layouts populate the Global Actions menu. - **[Get Global Publisher Layouts and Descriptions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-layouts-global-get.md)** Retrieves lists of global publisher layouts and their descriptions. Global publisher layouts customize the actions on global pages (like the Home page). In Lightning Experience, these layouts populate the Global Actions menu. - **[Return Headers for All Global Publisher Layouts](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-layouts-global-head.md)** Returns only the headers that are returned by a GET request to sObject Layouts resources. This gives you a chance to see header values ahead of time before retrieving the content of the resource. <!-- document id=1603a184c9f55b069ea0b3a13bfb6fea850648322beee958395e948735792860 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts.md --> # sObject Layouts Retrieves lists of page layouts and their descriptions. You can request information for all of a specific object’s layouts or for layouts associated with a specified record type on a specific object. - **[Get Layouts and Descriptions for a Specified Object](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-layouts-get.md)** Retrieves lists of layouts and their descriptions for a single object. - **[Return Layout Headers for a Specified Object](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-layouts-head.md)** Returns only the headers that are returned by a GET request to sObject Layouts resources. This gives you a chance to see header values ahead of time before retrieving the content of the resource. **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=2f4ede219a276d9405c9da88e47a36adc430c21497e86e7a474d786ef5a852b0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-layouts-multiple-rts.md --> # sObject Layouts for an Object With Multiple Record Types Retrieves lists of page layouts and their descriptions for objects that have more than one record type defined. <!-- document id=65052fadb9045a70fb16f922484f0e45ea78231b59c37657271016ccade50107 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-named-layouts.md --> # sObject Named Layouts Retrieves information about alternate named layouts for a given object. This resource is available in REST API version 31.0 and later. Use this resource to get information on a named layout for a given object. You must provide a valid named layout name as part of the resource URI. To get a list of named layouts for a given object, use the [sObject Describe](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-describe.md) resource and look for the “namedLayoutInfos” field in the response body. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/describe/namedLayouts/layoutName` **Formats:** JSON, XML **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/User/describe/namedLayouts/UserAlt -H "Authorization: Bearer token" ``` **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=65bad23cfa6c1dc18cbd2465716aa8412f2e13231dcdaf347786e71c1698ca94 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-platformaction.md --> # sObject PlatformAction Returns the description of the PlatformAction. PlatformAction is a virtual read-only object. It enables you to query for actions displayed in the UI, given a user, a context, device format, and a record ID. Examples include standard and custom buttons, quick actions, and productivity actions. This resource is available in API version 33.0 and later. The only thing you can do with this resource is [Query](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-query.md#query) it. ## Syntax **URI:** `/services/data/vXX.X/sobjects/PlatformAction` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=8804265ff5fff1f09549b2edb40314d9204bb037b607eed6a484f1c3517c164a url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-default-values.md --> # sObject Quick Action Default Values Retrieves the default values, including default field values, for a specific action on an object. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). - **[Get sObject Quick Action Default Values](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-default-values-get.md)** Returns a specific action’s default values, including field values. This resource is available in REST API version 28.0 and later. - **[Return Headers Using sObject Quick Action Default Values](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-default-values-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. <!-- document id=bf8de14f6b6b8eb49fc0fb14fb05e1ba3280951cf94917fcc542fc31be2480cd url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-default-values-id.md --> # sObject Quick Action Default Values by ID Evaluates the default values for a specific action on an object. Responses include default field values. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). - **[Get sObject Quick Action Default Values by ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-default-values-id-get.md)** Returns the default values for an action specific to the context_id object. This resource is available in REST API version 29.0 and later. - **[Return Headers Using sObject Quick Action Default Values by ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-default-values-id-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 29.0 and later. <!-- document id=3880fd7b492f0e7589ebc606725ee1e172dd44fb84008b9b3cbc338dfeb87f63 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-detail.md --> # sObject Quick Action Details Access the descriptive detail for a specific action on an object. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). - **[Get sObject Quick Action Details](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-detail-get.md)** Returns a specific action’s descriptive detail. This resource is available in REST API version 28.0 and later. - **[Return Headers Using sObject Quick Action Details](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-detail-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. <!-- document id=668b7fa2b0f51311d2b5cbe9c044572d14cd1ad7485e52b67766eaf807306b21 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions.md --> # sObject Quick Actions Access an object’s actions and the action details. This resource is available in REST API version 28.0 and later. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). - **[Get sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-get.md)** Returns a specific object’s actions as well as global actions. This resource is available in REST API version 28.0 and later. - **[Return Headers Using sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=91eab76bff47fdb4a2342634cab3fa0bde757634d468d44762e81da66808d369 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-relationships.md --> # sObject Relationships Accesses records by traversing object relationships via friendly URLs. You can retrieve, update, or delete the record associated with the traversed relationship field. If there are multiple related records, you can retrieve the complete set of associated records. This resource is available in REST API version 36.0 and later. - **[Get Records Using sObject Relationships](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-relationships-get.md)** Gets a record based on the specified object, record ID, and relationship field. The fields and field values of the record are returned in the response body. If there are multiple related records, you can retrieve the complete set of associated records. - **[Update Records Using sObject Relationships](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-relationships-patch.md)** Updates a parent record based on the specified object, record ID, and relationship field name. Field values provided in the request body replace the existing values in the record. Only a child-to-parent relationship can be traversed when you update records. - **[Delete Records Using sObject Relationships](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-relationships-delete.md)** Deletes a parent record based on the specified object, record ID, and relationship field name. Only a child-to-parent relationship can be traversed when you delete records. <!-- document id=287e8c2faf6910c4270959cf0bb5e2c0e8ba0db29a26a18866d6e10c6afd8698 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-relevant-items.md --> # sObject Relevant Items Gets the current user’s most relevant items. Relevant items include records for objects in the user’s global search scope and also most recently used (MRU) objects. Relevant items include up to 50 of the most recently viewed or updated records for each object in the user’s global search scope. **note:** The user’s global search scope includes the objects the user interacted with most in the last 30 days, including objects the user pinned from the search results page in the Salesforce Classic. Then, the resource finds more recent records for each most recently used (MRU) object until the maximum number of records, which is 2,000, is returned. This resource only accesses the relevant item information. Modifying the list of relevant items is not currently supported. This resource is available in API version 35.0 and later. ## Syntax **URI:** `/services/data/vXX.X/sobjects/relevantItems` **Formats:** JSON **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`lastUpdatedId`|Optional. Compares the entire current list of relevant items to a previous version, if available. Specify the `lastUpdatedId` value returned in a previous response.| |`sobjects`|Optional. To scope the results to a particular object or set of objects, specify the name for one or more sObjects.| |`sobject.lastUpdatedId`|Optional. Compares the current list of relevant items for this particular object to a previous version, if available. Specify the `lastUpdatedId` value returned in a previous response.| **Note:** sObject names are case-sensitive. **Note:** You can only specify the `sobject.lastUpdatedId` parameter for the sObjects specified in the `sobjects` parameter. **Response header** The response contains headers unique to this resource. |Name|Type|Description| |----|----|-----------| |`lastUpdatedId`|string|A unique code that can be used in subsequent calls to compare the results for a complete result set with the results in this response list.| |`newResultSetSinceLastQuery`|boolean (`true` or `false`)|If a response was previously requested for the current user, indicates whether the current response matches the previous response, or the one specified by a `lastUpdatedId`.| **Response body** The response contains an array of records for each object returned, including the following information for each record. |Name|Type|Description| |----|----|-----------| |`apiName`|string|The object’s unique name, such as `Account`| |`key`|ID|The first 3 characters of the sObject’s ID that indicates the object type.| |`label`|string|The object’s plural label, such as `Accounts`.| |`lastUpdatedId`|string|A unique code that can be used in subsequent calls to compare the results for the new result set with the current results for this object.| |`qualifiedApiName`|string|A unique external name for the sObject.| |`recordIds`|ID|A comma-separated list of IDs for the matching records.| ## Example See [Get Relevant Items](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-get-relevant-items.md#get-relevant-items). <!-- document id=d5e4f1e0f13429a78c6ba160977d282e9e15bc58daced38e7de8d92134633ce0 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-rich-text-image-retrieve.md --> # sObject Rich Text Image Get Gets the specified image data from a specific rich text area field in a given record. To get an image, you must have a record with an image uploaded to a rich text area field. **note:** The sObject Rich Text Image Get resource isn’t compatible with Composite API requests, because it returns binary data instead of data in JSON or XML formats. Instead, make individual sObject Blob Get requests to retrieve blob data. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/id/richTextImageFields/fieldName/contentReferenceId` **Formats:** Binary data **HTTP Method:** GET **Authentication:** `Authorization: Bearer token` **Parameters** |Parameter|Description| |---------|-----------| |`sObjectName`|Indicates the name of the standard object of the record.| |`id`|The ID of the object.| |`fieldName`|The name of the rich text area field.| |`contentReferenceId`|The reference ID that uniquely identifies an image within a rich text area field. You can obtain the reference by [retrieving information for the object](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-retrieve.md). The description shows the contents of the rich text area field. The `refid` parameter of the image (`0EMRM00000002Ip` in this example) is the `contentReferenceId`.| Example rich text area field contents: ```nolang { "attributes" : { "type" : "Lead", "url" : "/services/data/v68.0/sobjects/Lead/00QRM000003ZfDb2AK" }, "Id" : "00QRM000003ZfDb2AK", ... "ContactPhoto__c" : "Sarah Loehr and her two dogs. <img alt=\"Sarah Loehr.\" src=\"https://MyDomainName.file.force.com/servlet/rtaImage? eid=00QRM000003ZfDb& feoid=00NRM000001E73j& refid=0EMRM00000002Ip\"></img>" } ``` ## Example For an example of retrieving the blob data from a rich text area field, see [Get an Image from a Rich Text Area Field](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-sobject-rich-text-image-retrieve.md). **See Also** - [Object Reference for the Salesforce Platform](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/) <!-- document id=6c2cfa123af11d2865930726d01a00d246e03698d93fdefcfe82b6fcc9e47aa7 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-retrieve.md --> # sObject Rows Accesses records based on a specified object and record ID. Retrieves, updates, or deletes records based on the HTTP method. Use the GET method to retrieve records or specific field values, the DELETE method to delete records, or the PATCH method to update records. To create new records, use the [sObject Basic Information](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-basic-info.md) or [sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert.md) resources. - **[Get Records Using sObject Rows](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-retrieve-get.md)** Gets a record based on the specified object and record ID. The fields and field values of the record are returned in the response body. This resource can be used with external objects in API version 32.0 and later. - **[Update Records Using sObject Rows](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-retrieve-patch.md)** Updates a record based on the specified object and record ID. Field values provided in the request body replace the existing values in the record. This resource can be used with external objects in API version 32.0 and later. - **[Delete Records Using sObject Rows](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-retrieve-delete.md)** Deletes records based on the specified object and record ID. This resource can be used with external objects in API version 32.0 and later. <!-- document id=a5b7c86aaa1db49275348b34e3dec0a10e4d7922eb6c4a1b4f8840d06431feaf url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-upsert.md --> # sObject Rows by External ID Creates, retrieves, upserts, or deletes records based on the value of a specified external ID field. By using the PATCH method with this resource, you can send upsert requests to Salesforce. - **[Get Records Using sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert-get.md)** Retrieves a record based on the value of the specified external ID field. - **[Create Records Using sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert-post.md)** Creates a new record based on the field values included in the request body. This resource does not require the use of an external ID field. - **[Upsert Records Using sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert-patch.md)** Upserts a record based on the value of the specified external ID field. Based on whether the value of the external ID exists, the request either creates a record or updates an existing one. - **[Delete Records Using sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert-delete.md)** Deletes a record based on the value of the specified external ID field. - **[Return Headers Using sObject Rows by External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-upsert-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Rows by External ID resource. This gives you a chance to see returned header values of the GET request before retrieving the content itself. <!-- document id=7087ac65269a6418c40bbca72660432c0189611263c13458cd4921d11b6dfb6c url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-self-service-user-password.md --> # sObject Self-Service User Password Accesses self-service user passwords based on the specified user ID. Sets, resets, or gets the expiration status of a self-service user password based on the HTTP method. Use the GET method to retrieve a password’s expiration status, the POST method to set a password, or the DELETE method to initiate a password reset. - **[Get Self-Service User Password Expiration Status](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-self-service-user-password-get.md)** Retrieves a self-service user’s password expiration status based on the specified user ID. A True or False value is returned in the response body. This resource is available in REST API version 24.0 and later. - **[Set Self-Service User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-self-service-user-password-post.md)** Sets a self-service user’s password based on the specified user ID. The password provided in the request body replaces the user’s existing password. This resource is available in REST API version 24.0 and later. - **[Reset Self-Service User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-self-service-user-password-delete.md)** Initiates a password reset for a self-service user based on the specified user ID. The user’s current password becomes invalid and the user receives an email with a password reset link. To log in again, the user must finish resetting their password. This resource is available in REST API version 24.0 and later. - **[Return Headers Using sObject Self-Service User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-self-service-user-password-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Self-Service User Password resource. This operation allows you to see returned header values of the GET request before retrieving the content itself. This resource is available in REST API version 24.0 and later. <!-- document id=41f97048338d5300e9a48cc7825640ab288828d4800d72f3fbc42102667e02e2 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-approvallayouts-process.md --> # sObject Single Approval Process Retrieves an approval layout for a named approval process on a specified object. This resource is available in REST API version 30.0 and later. <!-- document id=c8cc3169038143c28aacee591dc79e1a652a1ef45de026dc68424e96a03c1022 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-sobject-quickactions-specific-action.md --> # sObject Specific Quick Actions Access a specific action for an object. By using the POST method with this resource, you can create records using an object’s quick actions. When working with actions, also refer to [Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-quickactions.md). - **[Get Specific sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-specific-action-get.md)** Gets a specific action for an object, as well as the action’s details. This resource is available in REST API version 28.0 and later. - **[Create Records Using Specific sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-specific-action-post.md)** Creates a record via the specified quick action based on the field values included in the request body. This resource is available in REST API version 28.0 and later. - **[Return Headers Using Specific sObject Quick Actions](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-quickactions-specific-action-head.md)** Returns only the headers that are returned by sending a GET request to the sObject Quick Actions resource. This gives you a chance to see the header values before retrieving the content of the resource. This resource is available in REST API version 28.0 and later. <!-- document id=6b1a2927176f9089dd5fb6af169e4ad1ea492d20a67b6207a4e70e01d6a03187 url=/developer/current/en-us/platform/api-rest/guides/resources/resources-composite-sobject-tree.md --> # sObject Tree Creates one or more sObject trees with root records of the specified type. An sObject tree is a collection of nested, parent-child records with a single root record. In the request data, you supply the record hierarchies, required and optional field values, each record’s type, and a reference ID for each record. Objects are created in the same order that they’re listed in the request. Upon success, the response contains the IDs of the created records. If an error occurs while creating a record, the entire request fails. In this case, the response contains only the reference ID of the record that caused the error and the error information. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire request counts as a single call toward your API limits. The request can contain the following: - Up to a total of 200 records across all trees - Up to five records of different types - sObject trees up to five levels deep Because an sObject tree can contain a single record, you can use this resource to create up to 200 unrelated records of the same type. When the request is processed and records are created, triggers, processes, and workflow rules fire separately for each of the following groups of records. - Root records across all sObject trees in the request - All second-level records of the same type—for example, second-level Contacts across all sObject trees in the request - All third-level records of the same type - All fourth-level records of the same type - All fifth-level records of the same type ## Syntax **URI:** `/services/data/vXX.X/composite/tree/sObjectName` **Formats:** JSON, XML **HTTP method:** POST **Authentication:** `Authorization: Bearer token` **Parameters:** None required **Request body:** [sObject Tree Request Body](https://developer.salesforce.com/docs/platform/api-rest/guide/requests-composite-sobject-tree.md) **Response body:** [sObject Tree Response Body](https://developer.salesforce.com/docs/platform/api-rest/guide/responses-composite-sobject-tree.md) ## Example - For an example of creating unrelated records of the same type, see [Create Multiple Records](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-composite-sobject-tree-flat.md). - For an example of creating nested records, see [Create Nested Records](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-composite-sobject-tree-create.md). <!-- document id=1fa3a957faac189e613a9fc5c5c4249112bc3ad97388b7094be12d064f450181 url=/developer/current/en-us/platform/api-rest/guides/resources/requests-composite-sobject-tree.md --> # sObject Tree Request Body Describes a collection of sObject trees to create with the sObject Tree resource. **important:** Where possible, we changed noninclusive terms to align with our company value of Equality. We maintained certain terms to avoid any effect on customer implementations. ## sObject Tree Collection Input The request body contains a `records` collection that includes sObject trees. **Properties** |Name|Type|Description|Required or Optional| |----|----|-----------|--------------------| |`records`|sObject Tree Input[]|Collection of record trees to create. Each tree’s root record type must correspond to the sObject specified in the sObject Tree URI.|Required| **Root XML Tag:** `<SObjectTreeRequest>` **JSON example** ```nolang { "records" :[{ "attributes" : {"type" : "Account", "referenceId" : "ref1"}, "name" : "SampleAccount", "phone" : "1234567890", "website" : "www.salesforce.com", "numberOfEmployees" : "100", "industry" : "Banking", "Contacts" : { "records" : [{ "attributes" : {"type" : "Contact", "referenceId" : "ref2"}, "lastname" : "Smith", "title" : "President", "email" : "sample@salesforce.com" },{ "attributes" : {"type" : "Contact", "referenceId" : "ref3"}, "lastname" : "Evans", "title" : "Vice President", "email" : "sample@salesforce.com" }] } },{ "attributes" : {"type" : "Account", "referenceId" : "ref4"}, "name" : "SampleAccount2", "phone" : "1234567890", "website" : "www.salesforce2.com", "numberOfEmployees" : "100", "industry" : "Banking" }] } ``` **XML example** ```nolang <SObjectTreeRequest> <records type="Account" referenceId="ref1"> <name>SampleAccount</name> <phone>1234567890</phone> <website>www.salesforce.com</website> <numberOfEmployees>100</numberOfEmployees> <industry>Banking</industry> <Contacts> <records type="Contact" referenceId="ref2"> <lastname>Smith</lastname> <title>President sample@salesforce.com Evans Vice President sample@salesforce.com SampleAccount2 1234567890 www.salesforce2.com 100 Banking ``` ## sObject Tree Input An sObject tree is a recursive data structure that contains a root record, its data, and its child records represented as other sObject trees. **Properties** |Name|Type|Description|Required or Optional| |----|----|-----------|--------------------| |`attributes`|Collection|Attributes for this record. The `attributes` property contains two required subproperties: `type` (this record’s type) and `referenceId` (reference ID for this record). The ID is case-sensitive and must be unique in the context of the request. Values must start with an alphanumeric character and contain only letters, numbers, or underscores (’\_’). In XML, include attributes inside the `records` element.|Required| |Required object fields|Depends on field|Required fields and field values for this record.|Required| |Optional object fields|Depends on field|Optional fields and field values for this record.|Optional| |Child relationships|sObject Tree Collection Input|This record’s child relationships, such as an account’s child contacts. Child relationships are either master-detail or lookup relationships. To view an object’s valid child relationships, use the sObject Describe resource or Schema Builder. The value of this property is an sObject Tree Collection Input that contains child sObject trees.|Optional| **Root XML Tag:** `` **JSON example** ```nolang { "attributes" : {"type" : "Account", "referenceId" : "ref1"}, "name" : "SampleAccount", "phone" : "1234567890", "website" : "www.salesforce.com", "NumberOfEmployees" : "100", "industry" : "Banking", "Contacts" : { "records" : [{ "attributes" : {"type" : "Contact", "referenceId" : "ref2"}, "lastname" : "Smith", "title" : "President", "email" : "sample@salesforce.com" },{ "attributes" : {"type" : "Contact", "referenceId" : "ref3"}, "lastname" : "Evans", "title" : "Vice President", "email" : "sample@salesforce.com" }] } } ``` **XML example** ```nolang SampleAccount 1234567890 www.salesforce.com 100 Banking Smith President sample@salesforce.com Evans Vice President sample@salesforce.com ``` # sObject Tree Response Body Describes the result of an sObject Tree request. **Properties** |Name|Type|Description| |----|----|-----------| |`hasErrors`|Boolean|`true` if an error occurred while creating a record; `false` otherwise.| |`results`|Collection|Upon success, `results` contains the reference ID of each requested record and its new record ID. Upon failure, it contains only the reference ID of the record that caused the error, error status code, error message, and fields related to the error. In the case of duplicate reference IDs, `results` contains one item for each instance of the duplicate ID.| **JSON example upon success** ```nolang { "hasErrors" : false, "results" : [{ "referenceId" : "ref1", "id" : "001D000000K0fXOIAZ" },{ "referenceId" : "ref4", "id" : "001D000000K0fXPIAZ" },{ "referenceId" : "ref2", "id" : "003D000000QV9n2IAD" },{ "referenceId" : "ref3", "id" : "003D000000QV9n3IAD" }] } ``` **XML example upon success** ```nolang false 001D000000K0fXOIAZ ref1 001D000000K0fXPIAZ ref4 003D000000QV9n2IAD ref2 003D000000QV9n3IAD ref3 ``` **JSON example upon failure** ```nolang { "hasErrors" : true, "results" : [{ "referenceId" : "ref2", "errors" : [{ "statusCode" : "INVALID_EMAIL_ADDRESS", "message" : "Email: invalid email address: 123", "fields" : [ "Email" ] }] }] } ``` **XML example upon failure** ```nolang true Email Email: invalid email address: 123 INVALID_EMAIL_ADDRESS ref2 ``` # sObject User Password Accesses user passwords based on the specified user ID. Sets, resets, or gets the expiration status of a user password based on the HTTP method. Use the GET method to retrieve a password’s expiration status, the POST method to set a password, or the DELETE method to initiate a password reset. - **[Get User Password Expiration Status](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-user-password-get.md)** Gets a user’s password expiration status based on the specified user ID. A True or False value is returned in the response body. This resource is available in REST API version 24.0 and later. - **[Set User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-user-password-post.md)** Sets a user’s password based on the specified user ID. The password provided in the request body replaces the user’s existing password. This resource is available in REST API version 24.0 and later. - **[Reset User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-user-password-delete.md)** Initiates a password reset for a user based on the specified user ID. The user’s current password becomes invalid and the user receives an email with a password reset link. To log in again, the user must finish resetting their password. This resource is available in REST API version 24.0 and later. - **[Return Headers Using sObject User Password](https://developer.salesforce.com/docs/platform/api-rest/guide/resources-sobject-user-password-head.md)** Returns only the headers that are returned by sending a GET request to the sObject User Password resource. This operation allows you to see returned header values of the GET request before retrieving the content itself. This resource is available in REST API version 24.0 and later. # sObjects Suggested Articles Returns results on suggested articles for a Case, Work Order, or Work Order Line. These suggestions are based on common keywords in the title, description, and other information that’s entered before the record has been saved and assigned an ID. This resource is available in REST API version 30.0 and later. Salesforce Knowledge must be enabled in your organization. The user must have the “View Articles” permission enabled. The articles suggested include only the articles the user can access, based on the data categories and article types the user has permissions to view. Articles are suggested based on a relevance algorithm. The `suggestedArticles` resource is designed to get the IDs of articles relevant to a case, work order, or work order line item. It’s intended to be used with other services that than use the IDs to get article data for display. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/suggestedArticles​?language=articleLanguage&subject=subject&description=description`. **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None required **Request parameters** |Parameter|Description| |---------|-----------| |`articleTypes`|Optional. Three-character ID prefixes indicating the desired article types. You can specify multiple values for this parameter in a single REST call, by repeating the parameter name for each value. For example, `articleTypes=ka0&articleTypes=ka1`.| |`categories`|Optional. The name of the data category group and the data category API name (not category title) for desired articles. The syntax is `categories={"Group":"Category"}`. Characters in the URL might need to be encoded. The same data category group can’t be specified more than once. However, you can specify multiple data category group and data category pairs. For example, `categories={"Regions":"Asia","Products":"Laptops"}.`| |`description`|Text of the description. Valid only for new records without an existing ID and required if `subject` is null. Article suggestions are based on common keywords in the subject, description, or both.| |`language`|Required. Language that the article is written in.| |`limit`|Optional. Specifies the maximum number of suggested articles to return.| |`publishStatus`|Optional. The article’s publication status. Valid values: `Draft`–Not published, `Online`–Published in Salesforce Knowledge, or `Archived`.| |`subject`|Text of the subject. Valid only for new records without an existing ID and required if `description` is null. Article suggestions are based on common keywords in the subject, description, or both.| |`topics`|Optional. The topic of returned articles. For example:` topics=outlook&topics=email`.| |`validationStatus`|Optional. The validation status of returned articles.| Example `categories`: ```nolang categories=%7B%22Regions%22%3A%22Asia%22%2C%22 Products%22%3A%22Laptops%22%7D ``` ## Example **Example Request** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Case/suggestedArticles? language=en_US&subject=orange+banana&articleTypes=ka0&articleTypes=ka1 -H "Authorization: Bearer token" ``` **Example Response Body** ```nolang [ { "attributes" : { "type" : "KnowledgeArticleVersion", "url" : "/services/data/v68.0/sobjects/KnowledgeArticleVersion/ka0D00000004CcQ" "Id" : "ka0D00000004CcQ" }, { "attributes" : { "type" : "KnowledgeArticleVersion", "url" : "/services/data/v68.0/sobjects/KnowledgeArticleVersion/ka0D00000004CXo" }, "Id" : "ka0D00000004CXo" } ] ``` # sObjects Suggested Articles by ID When you enter an article ID, you can retrieve records that offer similar information as the ID you entered. This resource is available in REST API version 30.0 and later. Salesforce Knowledge must be enabled in your organization. The user must have the “View Articles” permission enabled. The articles suggested include only the articles the user can access, based on the data categories and article types the user has permissions to view. Articles are suggested based on a relevance algorithm. The `suggestedArticles` resource is designed to get the IDs of articles relevant to a case, work order, or work order line item. It’s intended to be used with other services that than use the IDs to get article data for display. ## Syntax **URI:** `/services/data/vXX.X/sobjects/sObject/ID/suggestedArticles?language=articleLanguage` **Formats:** JSON, XML **HTTP methods:** GET **Authentication:** `Authorization: Bearer token` **Request body:** None required **Request parameters** |Parameter|Description| |---------|-----------| |`articleTypes`|Optional. Three-character ID prefixes indicating the desired article types. You can specify multiple values for this parameter in a single REST call, by repeating the parameter name for each value. For example, `articleTypes=ka0&articleTypes=ka1`.| |`categories`|Optional. The name of the data category group and the data category API name (not category title) for desired articles. The syntax is `categories={"Group":"Category"}`. Characters in the URL might need to be encoded. The same data category group can’t be specified more than one time. However, you can specify multiple data category group and data category pairs. For example, `categories={"Regions":"Asia","Products":"Laptops"}.`| |`description`|Text of the description. Valid only for new records without an existing ID and required if `subject` is null. Article suggestions are based on common keywords in the subject, description, or both.| |`language`|Required. Language that the article is written in.| |`limit`|Optional. Specifies the maximum number of suggested articles to return.| |`publishStatus`|Optional. The article’s publication status. Valid values: `Draft`–Not published, `Online`–Published in Salesforce Knowledge, or `Archived`.| |`subject`|Text of the subject. Valid only for new records without an existing ID and required if `description` is null. Article suggestions are based on common keywords in the subject, description, or both.| |`topics`|Optional. The topic of returned articles. For example:` topics=outlook&topics=email`.| |`validationStatus`|Optional. The validation status of returned articles.| Example `categories`: ```nolang categories=%7B%22Regions%22%3A%22Asia%22%2C%22 Products%22%3A%22Laptops%22%7D ``` ## Example **Example Response Body** ```nolang [ { "attributes" : { "type" : "KnowledgeArticleVersion", "url" : "/services/data/v68.0/sobjects/KnowledgeArticleVersion/ka0D00000004CcQ" "Id" : "ka0D00000004CcQ" }, { "attributes" : { "type" : "KnowledgeArticleVersion", "url" : "/services/data/v68.0/sobjects/KnowledgeArticleVersion/ka0D00000004CXo" }, "Id" : "ka0D00000004CXo" } ] ``` # social:profileViewer UI component that adds the Social Accounts and Contacts viewer to Account (including person account), Contact, or Lead detail pages. The viewer displays the record name, a profile picture, and the social network icons that allow users to sign in to their accounts and view social data directly in Salesforce. Social Accounts and Contacts must be enabled for your organization. Note that this component is only supported for Account, Contact, and Lead objects and can only be used once on a page. This component isn't available for Visualforce pages on Force.com sites. **note:** The Social Accounts, Contacts, and Leads feature is now unavailable. See [Twitter/X Public API Access](https://help.salesforce.com/s/articleView?id=000396136&type=1). ## Example This example displays the Social Accounts and Contacts viewer for a contact. ```visualforce ``` ## Attributes | Attribute Name | Attribute Type | Description | Required? | API Version | Access | | -------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------- | ----------- | ------ | | `entityId` | id | Entity ID of the record for which to display the Social Accounts and Contacts viewer; for example, Contact.Id. | Yes | 24.0 | | | `id` | String | An identifier that allows the component to be referenced by other components in the page. |   | 14.0 | global | | `rendered` | Boolean | A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. |   | 14.0 | global | # SOQL and SOSL |GOAL|Best Practice| |----|-------------| |Allow indexed searches when SOQL queries with multiple `WHERE` filters can’t use indexes|Decompose the query. If you use two indexed fields joined by an `OR` in the `WHERE` clause, your search results can exceed the index threshold. Break the query into two queries and join the results.| |Avoid querying on formula fields, which are computed in real time|If you have to query on formula fields, use formulas. Avoid filtering with formula fields that contain dynamic, non-deterministic references. See [Standard and Custom Indexed Fields](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-infrastructure-indexes.md#standard-and-custom-indexed-fields).| |Use the most appropriate language, SOQL or SOSL, for a given search|See [Using SOQL and SOSL](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-techniques-using-soql-and-sosl.md).| |Execute queries with null values in a `WHERE` filter for picklists or foreign key fields|Use values such as `NA` to replace `NULLS` options. (See [Using SOQL and SOSL](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-techniques-using-soql-and-sosl.md).)| |Design efficient custom query and search user interfaces|Use SOQL and SOSL where appropriate, keep queries focused, and minimize the amount of data being queried or searched. (See [Using SOQL and SOSL](https://developer.salesforce.com/docs/platform/salesforce-large-data-volumes-bp/guide/ldv-deployments-techniques-using-soql-and-sosl.md).)| |Build efficient SOQL and SOSL queries|Use filters and specific terms in your queries. For SOQL:
    • Use selective filters, which reduce the number of rows the Query Optimizer has to scan. For example, use filters that reference indexed fields and fields that have a wider range of possible values. If filters aren’t selective, the optimizer doesn’t use indexed columns.
    • When filtering on `FirstName` and `LastName`, use the `Name` field instead. For example, `Select id, Email from Lead where Name=’Sam Kennedy’`
    • Avoid negative filters. For example, `status !=’failed’` or `status != NULL`
    • Use `IN` instead of a large list of `OR` statements. For example, `id in (‘001xxx’,‘001xxy’, ‘001xxz’)`.
    • Avoid cross-object reference formula fields. Don’t filter on these objects. They aren’t indexable.
    For SOSL:
    • For SOSL, selective filters reduce the number of irrelevant results. If the filters aren’t selective and there are search terms matches for more than 2,000 records, results can be impacted by [search crowding](https://help.salesforce.com/s/articleView?id=ai.search_crowding_considerations.htm&type=5).
    • Don’t index custom objects that you don’t want searched. It adds to the number of records available to search, which can lead to search crowding.
    • Filter out objects you don’t want searched.
    • Use specific search terms.
    • Use targeted search groups. Search groups include NAME, EMAIL, and PHONE fields. For example, ` FIND ‘Avery Smith’ IN NAME FIELDS RETURNING Account(Id,Name), Lead(Id,Name)`
    | |Avoid timeouts on large SOQL queries|Tune the SOQL query, reducing query scope, and using selective filters. Consider using Bulk API 2.0 with [Bulk API 2.0 Query](https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/query_bulk_api_2_0.htm). If you’ve used the previous suggestions and still get timeouts, consider adding a [LIMIT clause](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_limit.htm) (starting with 100,000 records) to your queries. If using batch Apex for your queries, use chaining to get sets of records (using LIMIT) or consider [moving filter logic to the execute method](https://developer.salesforce.com/blogs/engineering/2013/02/force-com-batch-apex-and-large-data-volumes.html).| # SOQL and SOSL Limits for Search Queries | Feature | Limit | Limit Description | | --------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SOQL statements | Maximum length of SOQL statements | By default, 100,000 characters. For details on SOQL statement limits, including information on queries that involve external objects, see [Understanding Relationship Query Limitations](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm).

    Long, complex SOQL statements, such as statements that contain many formula fields, can result in a `QUERY_TOO_COMPLICATED` error. The error occurs because the statement is expanded internally when processed by Salesforce, even though the original SOQL statement is under the 100,000 character limit. To avoid this error, reduce the complexity of your SOQL statement.

    Page layouts in Lightning with more than 250 fields can also cause a `QUERY_TOO_COMPLICATED` error. Lightning uses auto-generated SOQL to retrieve fields for a record page layout, so the error can occur even if there isn't any customer-written SOQL.

    The character limit can also be reached by including too many currency fields. Currency fields require SOQL to use a format method, roughly doubling the field API name length for each currency field.

    The SOQL statement character limit does not apply when using SOQL with dynamic Apex. | | SOQL statements | Maximum number of junction IDs | 500 IDs per query. If a query includes 501 or more junction IDs, the query fails and returns the `MALFORMED_QUERY` exception. | | SOQL `WHERE` clause | Strings in SOQL `WHERE` clauses | 4,000 characters for each string within a `WHERE` clause. | | SOQL query results | Maximum rows returned | 2,000 results per request (API version 28.0 and later), unless you specify custom limits in the query. This limit includes results from child objects. Previous API versions return 200 results. When a query is executed from within an Apex class, additional limits apply. See [Apex Governor Limits](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm) for more information. | | SOQL query results | Availability | 2 days, including results in nested queries. | | SOQL query timeout | Maximum runtime for a SOQL query | 32 minutes total for both executing the operation and processing the results, but a query can time out at either the execution or processing stage. A query operation has 2 minutes to execute and 30 minutes to process results before timeout occurs. | | SOSL statements | Maximum length of SOSL statements | By default, 100,000 characters. This limit is tied to the SOQL statement character limit defined for your org. | | SOSL search query strings | Maximum length of `SearchQuery` string | If the `SearchQuery` string is longer than 10,000 characters, no result rows are returned. If `SearchQuery` is longer than 4,000 characters, any logical operators are removed. For example, the `AND` operator in a statement with a `SearchQuery` that's 4,001 characters defaults to the `OR` operator, which could return more results than expected. | | SOSL query results | Maximum rows returned | 2,000 results total (API version 28.0 and later), unless you specify custom limits in the query. This limit includes results from child objects. Previous API versions return 200 results. | | Relationship queries | Relationship query limits |
    • No more than 55 child-to-parent relationships can be specified in a query. A custom object allows up to 40 relationships, so you can reference all the child-to-parent relationships for a custom object in one query.
    • A single query of polymorphic fields can count multiple times against the child-to-parent relationship limit. For more information, see [Understanding Relationship Query Limitations](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_limits.htm).
    • No more than 20 parent-to-child relationships can be specified in a query.
    • In each specified relationship, no more than five levels can be specified in a child-to-parent relationship. For example, `Contact.Account.Owner.FirstName` (three levels).
    • In API version 57.0 and earlier, only two levels of parent-to-child relationship can be specified in a query.
    • In API version 58.0 and later, up to five levels of parent-to-child relationship can be queried via REST, SOAP, and Apex query calls for standard and custom objects. SOQL queries with five-level parent-to-child relationships aren't supported for big objects, external objects, or Bulk API and Bulk API 2.0.
    | | FOR VIEW and FOR REFERENCE | Maximum RecentlyViewed records allowed | The RecentlyViewed object is updated every time the logged-in user views or references a record. It is also updated when records are retrieved using the `FOR VIEW` or `FOR REFERENCE` clause in a SOQL query. To ensure that the most recent data is available, RecentlyViewed data is periodically truncated down to 200 records per object. RecentlyViewed data is retained for 90 days, after which it is removed on a periodic basis. | | OFFSET clause | Maximum number of rows skipped by OFFSET | The maximum offset is 2,000 rows. Requesting an offset greater than 2,000 results in a `NUMBER_OUTSIDE_VALID_RANGE` error. | | ORDER BY clause in SOQL statement | ORDER BY fields limit | The `ORDER BY` clause in the `SELECT` statement of a SOQL query controls the order of the query results, such as alphabetically beginning with z. If records are null, you can use `ORDER BY` to display the empty records first or last. | **See Also** - [_Salesforce Help_: Search Query Limits](https://help.salesforce.com/s/articleView?id=ai.search_query_limitations.htm&type=5) # SOQL and SOSL Reference Previous PDF Versions | API Version | Release | PDF | | ----------- | ---------- | -------------------------------------------------------------------------------------------------------- | | 68.0 | Winter '27 | [Download PDF](https://resources.docs.salesforce.com/264/latest/en-us/sfdc/pdf/salesforce_soql_sosl.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/salesforce_soql_sosl.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/salesforce_soql_sosl.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/salesforce_soql_sosl.pdf) | # SOQL Injection Sanitize user-controlled data passed into dynamic SOQL queries. SOQL or SOSL injection occurs when Apex code inserts user-controlled data into dynamic SOQL or SOSL queries without properly sanitizing the input. There are two scenarios to consider: - Changing the overall structure of the query - Changing the value of a query parameter Control these scenarios by invoking Apex code that prevents callers from accessing data they’re not entitled to. Consider this code: ```nolang @AuraEnabled public static List getAccountName(string userId) { if (FeatureManagement.checkPermission('readAccount')) { string query='SELECT Name FROM Account WHERE Id=\''+ userId + '\''; return database.query(query); } } ``` The user potentially gains control over the query and accesses more information than they’re entitled to. The return value of the query doesn’t limit the information the user can access. The user can submit a string, such as : ```nolang userId = '0035Y00003pPJiNQAW\' OR AnnualRevenue>100000.00 OR Name=\'a' // 0035Y00003pPJiNQAW is any id to any object that is not an account ``` The return value of the query names all the accounts with an annual revenue in excess of $100,000, which is not what the developer intended to return to the caller. Fixing SOQL or SOSL injection requires the appropriate contextual encoding. Don’t apply `String.escapeSingleQuotes` to every user input. Rather, sanitize fields based on where they appear in the SOQL or SOSL query. - For variables in WHERE (SOQL), ORDER BY (SOQL), WITH (SOSL), or FIND (SOSL) clauses, use bound variables: ```nolang string query='SELECT Name FROM Account WHERE Id=:userId'; ``` - For field and table names, call `isAccessible` on the `describeResult` of the field. Or to enforce declarative policies, use your own procedural logic to limit the field or table names to what your security policy allows. - For parameters in quoted strings, use bind variables. Don’t use bind variables or `String.escapeSingleQuote` to sanitize table names and field names, or any parameters that don’t appear in a quoted context. - For other primitive types, cast the user input into a boolean, integer, Id, or other primitive (non-string) type. Be aware that the WITH SECURITY_ENFORCED keyword doesn’t sanitize WHERE clauses, only SELECT and FROM clauses, so it isn’t a sanitizer for SOQL or SOSL injection attacks. # SOQL Injection In other programming languages, the previous flaw is known as SQL injection. Apex doesn’t use SQL, but uses its own database query language, SOQL. SOQL is simpler and more limited in functionality than SQL. The risks are lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection. SQL/SOQL injection takes user-supplied input and uses those values in a dynamic SOQL query. If the input isn’t validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands. ## SOQL Injection Vulnerability in Apex Here’s a simple example of Apex and Visualforce code vulnerable to SOQL injection. ```apex `, `>=`, `<`, `<=`, and `!=` - `LIKE`, including wild cards - `AND` - `OR` when on the same column with `LIKE` and `=` operations - You can use `ORDER BY` only with non-relationship fields. - You can use `ORDER BY`, `ASC`, and `DESC` with multiple (non-relationship) fields. - Metadata relationship fields support all standard relationship queries. **Note:** `OR` can’t be used as a compound filter when child filters are on two different columns. **Data 360 Objects:** - To prevent large queries from crashing the app server, Data 360 limits Salesforce Object Query Language (SOQL) results to 12-MB. SOQL returns the results up to the size limit with a query more link to paginate through the rest of the results. If a single query result exceeds the size limit, SOQL rejects the query and you can’t retrieve the results. - Queries that contain aggregate functions don’t support currency fields even when the fields are outside the aggregate functions. - For currency field query limitations, see [Considerations for Querying Currency Data Using SOQL](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-consider-cur-data.md). - These aggregate functions are available for querying data model objects (DMOs) and data lake objects (DLOs). - `AVG(fieldName)` - `SUM(fieldName)` - `COUNT()` - `COUNT(fieldName)` - `MIN(fieldName)` - `MAX(fieldName)` - You can’t query calculated insight objects (CIOs). - Use the [`SET OPTIONS`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-set-options.md) clause to specify a dataspace when querying a data lake object (DLO) or to distinguish between `NULL` and empty string (`''`) when querying a data lake object (DLO) or data model object (DMO). - Data Cloud objects have these limitations related to the `Id` field. - You can’t use the `Id` field in the `HAVING` clause in `HAVING Id` or `HAVING COUNT(Id)`. - You can’t use the `Id` field in the `GROUP BY` clause in `GROUP BY Id` or `GROUP BY COUNT(Id)`. - Data Cloud objects have these limitations related to the `HAVING` clause. - You can’t use the `HAVING` clause with the `IN` operator. For example, this query isn’t supported: `SELECT AVG(Number) FROM Dmo HAVING AVG(Number) IN (0, 10, 20)` - You can’t use the `HAVING` clause when comparing to a null value. For example, this query isn’t supported: `SELECT AVG(Number) FROM Dmo HAVING AVG(Number) != NULL` - You can only use the default strategy for string collation as defined by [Unicode Root Collation](https://unicode.org/reports/tr35/tr35-collation.html#Root_Collation) in the Unicode Technical Standard. String collations include locale-based collations and collation strategies defined in the SOQL query. Custom collations aren’t supported. Comparison operators (`>`, `<`, `>=`, and `<=`) that are used with string collations aren’t supported for Data Cloud queries. For example, this query isn’t supported: `SELECT Text_Field FROM Dmo WHERE Text_Field > 'SomeValue'` - Child-to-parent object relationships aren’t supported. - Semi-join queries between two DMOs have these limitations. - You must always use the lookup fields when constructing the semi-join, irrespective of the actual relationship fields. The structure of the query depends on if the parent is in the outer or inner query. - Outer query on parent DMO: ```nolang SELECT … FROM WHERE ID IN ( SELECT rel_…__c FROM … ) ``` - Inner query on parent DMO: ```nolang SELECT … FROM WHERE rel_…__c IN ( SELECT Id FROM … ) ``` - Standard SOQL semi-join limitations apply. See [Considerations for Semi-Join and Anti-Join Queries](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-comparisonoperators.md#considerations-for-semi-join-and-anti-join-queries). - Semi-joins between an outer child DMO and an inner parent CRM object have these restrictions. - Both direct and identity resolution-based relationships are supported. - The child DMO must look up the parent sObject’s ID field. - Example query: ```nolang SELECT … FROM WHERE rel_…__c IN ( SELECT Id FROM … ) ``` - The inner CRM object query is limited to 2,000 records. If more than 2,000 records are returned, the query returns an error. - The DMO outer query can't trigger `queryMore()`. If it does, the query returns an error. - Standard SOQL semi-join limitations apply. See [Considerations for Semi-Join and Anti-Join Queries](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-comparisonoperators.md#considerations-for-semi-join-and-anti-join-queries). - Semi-joins between an outer parent CRM object and inner child DMO have these restrictions: - Only direct DMO relationships between CRM and DMO objects are supported. Identity resolution-based relationships aren't supported. - The child DMO must look up the parent sObject's ID field. - Example query: ```nolang SELECT ... FROM WHERE Id IN ( SELECT rel_...__c FROM ... ) ``` - The inner CRM object query is limited to 2,000 records. If more than 2,000 records are returned, the query returns an error. - The DMO outer query can't trigger `queryMore()`. If it does, the query returns an error. - Standard SOQL semi-join limitations apply. **External objects:** - A subquery that involves external objects can fetch up to 1,000 rows of data. - Each SOQL query can have up to 4 joins across external objects and other types of objects. Each join requires a separate round trip to the external system when executing the query. Expect longer response times for each join in a query. - External objects don’t support the following aggregate functions and clauses. - `AVG()` function - `COUNT(fieldName)` function (however, `COUNT()` is supported) - `HAVING` clause - `GROUP BY` clause - `MAX()` function - `MIN()` function - `SUM()` function - External objects also don’t support the following. - `EXCLUDES` operator - `FOR VIEW` clause - `FOR REFERENCE` clause - `INCLUDES` operator - `LIKE` operator - `toLabel()` function - `TYPEOF` clause - `WITH` clause The following limits apply only to the OData 2.0 and 4.0 adapters for Salesforce Connect. - External objects have the following limitations for the `ORDER BY` clause. - `NULLS FIRST` and `NULLS LAST` are ignored. - External objects don’t support the `ORDER BY` clause in relationship queries. - The `COUNT()` aggregate function is supported only on external objects whose external data sources have `Request Row Counts` enabled. Specifically, the response from the external system must include the total row count of the result set. The following limits apply only to custom adapters for Salesforce Connect. - Location-based SOQL queries of external objects aren’t supported. - If a SOQL query of an external object includes the following, the query fails. - `convertCurrency()` function - `UPDATE TRACKING` clause - `UPDATE VIEWSTAT` clause - `USING SCOPE` clause - In an `ORDER BY` clause, the following are ignored. - `NULLS FIRST` syntax - `NULLS LAST` syntax - In Apex tests, use dynamic SOQL to query external objects. Tests that perform static SOQL queries of external objects fail. **KnowledgeArticleVersion:** - Filter on a single value of `PublishStatus` for best results. To find all versions of each article, omit the `PublishStatus` filter, but do filter on one or more primary key IDs. To retrieve all archived versions for a given article, specify a SOQL filter where `IsLatestVersion` is `false`. - In API version 46.0 and earlier, queries without a filter on `PublishStatus` return published articles by default. In API version 47.0 and later, draft, published, and archived articles are returned when Lightning Knowledge is enabled. - To support security, only users with the “View Draft Articles” permission see articles whose `PublishStatus` value is `Draft`. Similarly, only users with the “View Archived Articles” permission see articles whose `PublishStatus` value is `Archived` - Archived article versions are stored in the `Knowledge__kav` object. To query archived article versions, specify the article `Id` and set `IsLatestVersion='0'`. - You can’t use binding variables in Apex SOQL statements with KnowledgeArticleVersion objects. For example, the following SOQL statement causes a compilation error. ```soql final String PUBLISH_STATUS_ONLINE = 'Online'; List articles = [ SELECT Id FROM Knowledge__kav WHERE PublishStatus = :PUBLISH_STATUS_ONLINE ]; ``` Instead, use dynamic SOQL as follows. See [Dynamic SOQL](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm) in _Apex Developer Guide_. ```soql final String PUBLISH_STATUS_ONLINE = 'Online'; final String q = 'SELECT Id, PublishStatus FROM Knowledge__kav WHERE PublishStatus = :PUBLISH_STATUS_ONLINE'; List articles = Database.query(q); ``` **NewsFeed:** - No SOQL limit if logged-in user has “View All Data” permission. If not, specify a LIMIT clause of 1,000 records or fewer. - SOQL ORDER BY on fields using relationships is not available. Use ORDER BY on fields on the root object in the SOQL query. **UserProfileFeed:** - No SOQL limit if logged-in user has “View All Data” permission. If not, specify a LIMIT clause of 1,000 records or fewer. - SOQL ORDER BY on fields using relationships is not available. Use ORDER BY on fields on the root object in the SOQL query. Also, a SOQL query must include `WITH UserId = {userId]`. **Vote:** - `ParentId = [single ID]` - `Parent.Type = [single type]` - `Id = [single ID]` - `Id IN = [list of IDs]` For other SOQL limits, see [SOQL and SOSL Limits](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm) in the _Salesforce Developer Limits and Allocations Quick Reference_. # SOQL SELECT Examples The following are examples of text searches that use SOQL. | Type of Search | Examples | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | Simple query | `SELECT Id, Name, BillingCity FROM Account` | | `WHERE` | `SELECT Id FROM Contact WHERE Name LIKE 'A%' AND MailingCity = 'California'` | | `ORDER BY` | `SELECT Name FROM Account ORDER BY Name DESC NULLS LAST` | | `LIMIT` | `SELECT Name FROM Account WHERE Industry = 'media' LIMIT 125` | | `ORDER BY` with `LIMIT` | `SELECT Name FROM Account WHERE Industry = 'media' ORDER BY BillingPostalCode ASC NULLS LAST LIMIT 125` | | `count()` | `SELECT COUNT() FROM Contact` | | `GROUP BY` | `SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource` | | `HAVING` | `SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) > 1` | | `OFFSET` with `ORDER BY` | `SELECT Name, Id FROM Merchandise__c ORDER BY Name OFFSET 100` | | `OFFSET` with `ORDER BY` and `LIMIT` | `SELECT Name, Id FROM Merchandise__c ORDER BY Name LIMIT 20 OFFSET 100` | | Relationship queries: child-to-parent | `SELECT Contact.FirstName, Contact.Account.Name FROM Contact` | | Relationship queries: parent-to-child | `SELECT Name, (SELECT LastName FROM Contacts) FROM Account` | | Relationship query with `WHERE` | `SELECT Name, (SELECT LastName FROM Contacts WHERE CreatedBy.Alias = 'x') FROM Account WHERE Industry = 'media'` | | Relationship query: child-to parent with custom objects | `SELECT Id, FirstName__c, Mother_of_Child__r.FirstName__c FROM Daughter__c WHERE Mother_of_Child__r.LastName__c LIKE 'C%'` | | Relationship query: parent to child with custom objects | `SELECT Name, (SELECT Name FROM Line_Items__r) FROM Merchandise__c WHERE Name LIKE ‘Acme%’` | | Relationship queries with polymorphic key | `SELECT Id, Owner.Name FROM Task WHERE Owner.FirstName like 'B%'` | | Polymorphic relationship queries using `TYPEOF` | `SELECT TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate ELSE Name, Email END FROM Event` | | Relationship queries with aggregate | `SELECT Name, (SELECT CreatedBy.Name FROM Notes) FROM Account` | | Simple query: the UserId and LoginTime for each user | `SELECT UserId, LoginTime from LoginHistory` | | Relationship queries with number of logins per user in a specific time range | `SELECT UserId, COUNT(Id) from LoginHistory WHERE LoginTime > 2010-09-20T22:16:30.000Z AND LoginTime < 2010-09-21T22:16:30.000Z GROUP BY UserId` | | Query to retrieve the RecordType per user | `SELECT Id, Name, IsActive, SobjectType, DeveloperName, Description FROM RecordType` | Additional relationship query example (child-to-parent): ```soql SELECT Id, Name, Account.Name FROM Contact WHERE Account.Industry = 'media' ``` Additional relationship query example (parent-to-child): ```soql SELECT Account.Name, (SELECT Contact.LastName FROM Account.Contacts) FROM Account ``` Additional relationship query examples with polymorphic key: ```soql SELECT Id, Who.FirstName, Who.LastName FROM Task WHERE Owner.FirstName LIKE 'B%' ``` ```soql SELECT Id, What.Name FROM Event ``` Additional relationship query example with aggregate: ```soql SELECT Amount, Id, Name, (SELECT Quantity, ListPrice, PricebookEntry.UnitPrice, PricebookEntry.Name FROM OpportunityLineItems) FROM Opportunity ``` **Note:** If a user doesn’t have Read access to the object to which a record type belongs, that record type isn’t returned in the query results. **note:** Apex requires that you surround SOQL and SOSL statements with square brackets to use them in your statements. You can use Apex script variables and expressions when preceded by a colon (`:`). # SOQL SELECT Functions Use functions in SOQL queries to generate reports for analysis, apply localized formatting to standard and custom fields, group or filter data by date periods, and more. | Functions | Description | | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | [Aggregate Functions](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-agg-functions.md) | Use aggregate functions in a GROUP BY clause in SOQL queries to generate reports for analysis. | | [`convertCurrency()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-querying-currency-fields.md) | Use `convertCurrency()` in SOQL queries to convert currency fields to the user’s currency. | | [`convertTimezone()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-convert-time-zone.md) | Use `convertTimezone()` in a date function of SOQL queries to convert dateTime fields to the user’s time zone. | | [Date Functions](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-date-functions.md) | Use date functions in SOQL queries to group or filter data by date periods such as day, calendar month, or fiscal year. | | [`FORMAT()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-format.md) | Use `FORMAT()` in SOQL queries to apply localized formatting to standard and custom number, date, time, and currency fields. | | [`GROUPING(fieldName)`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-grouping.md) | Use GROUPING(fieldName) in SOQL queries to identify subtotals. | | [`toLabel()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-tolabel.md) | Use `toLabel()` to translate SOQL query results into the language of the user who submits the query. | # SOQL SELECT Syntax SOQL query syntax consists of a required `SELECT` statement followed by one or more optional clauses, such as `TYPEOF`, `WHERE`, `WITH`, `GROUP BY`, and `ORDER BY`. The SOQL SELECT statement uses the following syntax: ```soql SELECT fieldList [subquery][...] [TYPEOF typeOfField whenExpression[...] elseExpression END][...] FROM objectType[,...] [USING SCOPE filterScope] [WHERE conditionExpression] [WITH [DATA CATEGORY] filteringExpression] [GROUP BY {fieldGroupByList|ROLLUP (fieldSubtotalGroupByList)|CUBE (fieldSubtotalGroupByList)} [HAVING havingConditionExpression] ] [ORDER BY fieldOrderByList {ASC|DESC} [NULLS {FIRST|LAST}] ] [LIMIT numberOfRowsToReturn] [OFFSET numberOfRowsToSkip] [{FOR VIEW | FOR REFERENCE} ] [UPDATE {TRACKING|VIEWSTAT} ] [SET OPTIONS (optionName = optionValue [, optionName = optionValue])] [FOR UPDATE] ``` | Syntax | Description | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fieldList subquery` | Specifies a list of one or more fields, separated by commas, that you want to retrieve from the specified object. The bold elements in the following examples are fieldlist values: `SELECT Id, Name, BillingCity FROM Account`, `SELECT count() FROM Contact`, `SELECT Contact.Firstname, Contact.Account.Name FROM Contact`, or `SELECT FIELDS(STANDARD) FROM Contact`. Use valid field names and include read-level permissions for each specified field. The fieldList defines the ordering of fields in the query results. If the query traverses a relationship, fieldList can include a subquery. The fieldlist can also be an aggregate function, such as `COUNT()` and `COUNT(fieldName)`, or be wrapped in the [toLabel()](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-tolabel.md) function to translate returned results. See [`SELECT`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-fields.md) for more information. | | `typeOfField` | A polymorphic relationship field in `objectType` or a polymorphic field in a parent of `objectType` that can reference multiple object types. For example, the `Who` relationship field of a Task can be a Contact or a Lead.`typeOfField` can’t reference a relationship field that is also referenced in `fieldList`. See `TYPEOF` for more information. | | `whenExpression` | A clause of the form `WHEN whenObjectType THEN whenFieldList`. You can have one or more `whenExpression` clauses inside a `TYPEOF` expression. See `TYPEOF` for more information. | | `elseExpression` | A clause of the form `ELSE elseFieldList`. This clause is optional inside a `TYPEOF` expression. See `TYPEOF` for more information. | | `objectType` | Specifies the type of object that you want to `query()`. Provide a valid object, such as Account, and must have read-level permissions to that object. | | `filterScope` | Available in API version 32.0 and later. Specifies the `filterScope` for limiting the results of the query. | | `conditionExpression` | If `WHERE` is specified, determines which rows and values in the specified object (objectType) to filter against. If unspecified, the `query()` retrieves all the rows in the object that are visible to the user. | | `filteringExpression` | If `WITH DATA CATEGORY` is specified, the `query()` only returns matching records that are associated with the specified data categories and are visible to the user. If unspecified, the `query()` returns the matching records that are visible to the user. The `WITH DATA CATEGORY` clause only filters objects of type `Question` (to query questions) or `KnowledgeArticleVersion` (to query articles). See [`WITH DATA CATEGORY`. ](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-with-datacategory.md#with-data-category) If `WITH DATA CATEGORY` isn’t specified, filteringExpression can be used to enforce field- and object-level permission or to specify user- or system-mode access in Apex code. Salesforce recommends that you enforce field- and object-level security permissions by using `WITH USER_MODE` because it has fewer limitations than `WITH SECURITY_ENFORCED`. | | `fieldGroupByList` | Available in API version 18.0 and later. Specifies a list of one or more fields, separated by commas, that are used to group the query results. A `GROUP BY` clause is used with aggregate functions to summarize the data. This clause also lets you roll up query results rather than having to process the individual records in your code. See `GROUP BY`. | | `fieldSubtotalGroupByList` | Available in API version 18.0 and later. Specifies a list of up to three fields, separated by commas, that are used to group the query results. The results include extra subtotal rows for the grouped data. See `GROUP BY ROLLUP` and `GROUP BY CUBE`. | | `havingConditionExpression` | Available in API version 18.0 and later. If the query includes a `GROUP BY` clause, this conditional expression filters the records that the GROUP BY returns. See `HAVING`. | | `fieldOrderByList` | Specifies a list of one or more fields, separated by commas, that are used to order the query results. | Example fieldList with a subquery: ```codesegment SELECT Account.Name, (SELECT Contact.LastName FROM Account.Contacts) FROM Account ``` **SECURITY_ENFORCED:** Use the `WITH SECURITY_ENFORCED` clause to filter records based on user access permissions on fields or objects being queried within Apex code. See [Filter SOQL Queries Using WITH SECURITY_ENFORCED](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_with_security_enforced.htm) in the _Apex Developer Guide_. **USER_MODE** or **SYSTEM_MODE:** Specify user mode or system mode access for Apex database operations. Apex code runs in system mode by default, which means that it runs with substantially elevated permissions over the user running the code. To enhance the security context of Apex, you can specify user mode access using `WITH USER_MODE`. Field-level security (FLS) and object permissions of the running user are respected and sharing rules are applied in user mode, unlike in system mode. See [Enforce User Mode for Database Operations](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_enforce_usermode.htm) in the _Apex Developer Guide_. Example fieldOrderByList: ```codesegment SELECT Id, LastName, FirstName FROM Contact ORDER BY LastName, FirstName ``` ## Implementation Tips for SELECT Statement - **Statement Character Limit**—By default, SOQL statements can't exceed 100,000 characters in length. For SOQL statements that exceed this maximum length, the API returns a `MALFORMED_QUERY` exception code; no result rows are returned. **note:** Long, complex SOQL statements, such as statements that contain many formula fields, can result in a `QUERY_TOO_COMPLICATED` error. The error occurs because the statement is expanded internally when processed by Salesforce, even though the original SOQL statement is under the 100,000 character limit. To avoid this error, reduce the complexity of your SOQL statement. Page layouts in Lightning with more than 250 fields can also cause a `QUERY_TOO_COMPLICATED` error. Lightning uses auto-generated SOQL to retrieve fields for a record page layout, so the error can occur even if there isn’t any customer-written SOQL. The character limit can also be reached by including too many currency fields. Currency fields require SOQL to use a format method, roughly doubling the field API name length for each currency field. The SOQL statement character limit does not apply when using SOQL with dynamic Apex. - **Statements Returning Many Results**—If a SELECT statement returns a large amount of data per record, SOQL automatically reduces the number of results. The number of results can also vary based on how a SOQL query is called and on the complexity of the query. When you search a list view, only the first 2,000 records in the list are searched. If the object contains formula fields, derived fields, or CLOB or BLOB fields, large volumes of data can also be returned. To retrieve all the pages of results, use one of these methods: - In SOQL, if you use OFFSET and LIMIT in your SOQL query, the number of records returned can be less than LIMIT. Check the number of returned results and adjust OFFSET as required. Don’t increment OFFSET by LIMIT. - In SOAP API, use [`queryMore()`.](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_querymore.htm#topic-title) - In REST API, use the nextRecordsUrl returned by `/query` and `/queryAll`. - In Bulk API 2.0, use the Sforce-Locator response header that is returned in the job’s results. - **Localized Results**—SELECT statements can include the [toLabel()](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-tolabel.md), [`convertCurrency()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-querying-currency-fields.md), and [`FORMAT()`](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-soql-select-format.md#format-) functions in support of localized fields. - **Dynamic SOQL in Apex**—Apex requires that you surround SOQL and SOSL statements with square brackets to use them in your statements. You can use Apex script variables and expressions when preceded by a colon (`:`). - **Ordered Results**—The order of results isn’t guaranteed unless you use an `ORDER BY` clause in a query. - **Picklist Values**—In API version 39.0 and later, query for picklist values by the value’s API name, which can be different from the actual value. - **Avoid Query Timeouts**—Consider using [`WHERE` ](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_conditionexpression.htm) or [`WITH` ](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_with.htm) clauses to reduce the query operation time. In REST API, you can also try the `explain` parameter (beta) to get information on query processing. For more information, see [Get Feedback on Query Performance](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query_explain.htm) in the _REST API Developer Guide._ **See Also** - [_Salesforce Developer Limits and Allocations Quick Reference_: SOQL and SOSL Limits for Search Queries](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm) # SoqlWhereCondition Contains information about SOQL filter conditions for a list view. Each condition listed in SoqlWhereCondition represents a condition expression in a SOQL WHERE clause that compares a field value to a comparison value using a condition operator. Each condition contains the following properties. |Name|Type|Description| |----|----|-----------| |`field`|string|The object field used by the filter condition.| |`operator`|soqlOperator|The filter operation. Operations include:
    • equals—Condition is true if the field value equals the specified value. String comparisons using the equals operator are case sensitive for unique case-sensitive fields and case insensitive for all other fields.
    • excludes—Condition is true for multi-select picklist fields if the selected field values are not in the list of condition values.
    • greaterThan—Condition is true if the field value is greater than the specified value.
    • greaterThenOrEqualTo—Condition is true if the field value is greater than or equal to the specified value.
    • in—Condition is true if the field value equals any specified value in the values list.
    • includes—Condition is true for multi-select picklist fields if the selected field values are in the list of condition values.
    • lessThan—Condition is true if the field value is less than the specified value.
    • lessThanOrEqualTo—Condition is true if the field value is less than or equal to the specified value.
    • like—Condition is true if the field value matches the specified value, using character matching logic described in [Comparison Operators](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_comparisonoperators.htm) in the *SOQL and SOSL Reference*.
    • notEquals—Condition is true if the field value doesn’t equal the specified value.
    • notIn—Condition is true if the field value doesn’t equal any specified value in the values list.
    • notLike—Condition is true if the field value doesn’t match the specified value using the character matching logic described in [Comparison Operators](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_comparisonoperators.htm) in the *SOQL and SOSL Reference*. Available in API version 41.0 and later.
    • within—Condition is true if the field value location is within the value distance using a location-based comparison. For more information, see [Location-Based SOQL Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_geolocate.htm) in the *SOQL and SOSL Reference*.
    | |`values`|string[]|A list of one or more values used to compare with the field value using the `operator` comparison logic.| ## Evaluating SoqlWhereConditions In the SOAP API, Salesforce uses subclasses of SoqlWhereCondition to represent different categories of conditions. Use your development language’s type comparison functionality (such as Java’s `instanceof` operator) to determine which subclass is used for a particular instance of SoqlWhereCondition. The SoqlConditionGroup subclass represents a group of SOQL WHERE clause conditions and uses the following properties. |Name|Type|Description| |----|----|-----------| |`conditions`|condition[]|List of filter conditions. If the list view uses filter logic, each logical filter group is represented with a conditions list.| |`conjunction`|soqlConjunction|A conjunction operation that describes the filter logic to use for multiple conditions in a logical filter group. Values include:
    • and—All conditions must be true for the overall SoqlWhereCondition.
    • or—One of the conditions must be true for the overall SoqlWhereCondition.
    | The SoqlNotCondition subclass represents a special use of the `like` operator. In API version 40.0 and earlier, when evaluating a SoqlWhereCondition that was created using a `not like` operator (displayed as **does not contain** in the UI), the operator value in the condition is `like`. Salesforce also uses the SoqlNotCondition subclass of SoqlWhereCondition to represent the complete condition. The following example uses Java’s `instanceof` operator to determine whether a `not like` operation is specified. ```java if (resultSoqlWhereCondition instanceof SoqlNotCondition) { // condition is really NOT condition // if operator is "like", this condition really means "not like" ... } ``` In API version 41.0 and later, the `notLike` operator is used instead of SoqlNotCondition and a `like` operator. The `notLike` operator is available only for list views. You can’t use it in SOQL queries used in other Salesforce features. # Sort Optimization on a Query ## Situation The customer had the following query. ```soql SELECT Id,Product_Code__c FROM Customer_Product__c WHERE CreatedDate = Last_N_Days:3 ``` The query was looking for all the records created in the last three days, but the amount of data in the object exceeded the threshold for standard indexes: 30% of the total records up to one million records. The query performed poorly. ## Solution The query was rewritten as: ```soql SELECT Id,Product_Code__c FROM Customer_Product__c WHERE CreatedDate = Last_N_Days:3 ORDER BY CreatedDate LIMIT 99999 ``` In this query, the threshold checks were not done, and the `CreatedDate` index was used to find the records. This kind of query returns a maximum of 99,999 records in the order that they were created within the last three days, assuming that 99,999 or fewer records were created during the last three days. **note:** In general, when querying for data that has been added over the `Last_N_Days`, if you specify an `ORDER BY` query on an indexed field with a limit of fewer than 100,000 records, the `ORDER BY` index is used to do the query. # SOSL Limits on External Object Search Results SOSL applies specific limits to external objects in search results. - To include an external object in SOSL and Salesforce searches, enable search on both the external object and the external data source. However, syncing always overwrites the external object’s search status to match the search status of the external data source. - Only text, text area, and long text area fields on external objects can be searched. If an external object has no searchable fields, searches on that object return no records. - External objects don’t support the following. - `INCLUDES` operator - `LIKE` operator - `EXCLUDES` operator - `toLabel()` function - External objects also don’t support Salesforce Knowledge-specific clauses, including the following. - `UPDATE TRACKING` clause - `UPDATE VIEWSTAT` clause - `WITH DATA CATEGORY` clause - External objects must be specified explicitly in a `RETURNING` clause to be returned in search results. For example: ```soql FIND {MyProspect} RETURNING MyExternalObject, MyOtherExternalObject ``` - Text strings must be 100 or fewer characters. The following limits apply only to the OData 2.0 and 4.0 adapters for Salesforce Connect. - The OData adapters for Salesforce Connect don’t support logical operators in a `FIND` clause. We send the entire search query string to the external system as a case-sensitive single phrase after removing all ASCII punctuation characters except hyphens (-). For example, `FIND {MyProspect OR “John Smith”}` searches for the exact phrase “MyProspect OR John Smith”. The following limits apply only to custom adapters for Salesforce Connect. - The `convertCurrency()` function isn’t supported in SOSL queries of external objects. - `WITH` clauses aren’t supported in SOSL queries of external objects. # SOSL Limits on Search Results The search engine limits the number of records analyzed at each stage of the search process. Sometimes, these limits cause a matching record to be excluded from a user’s results. This image illustrates how the search engine processes SOSL searches and limits results. Each color represents an object, and each raindrop represents some records. The numbers correspond to this flow: 1. The search engine looks for matches to the search term across a maximum of 2,000 records (this limit starts with API version 28.0). 2. If you query one object only, a maximum of 250 records are returned. To return up to 2,000 results, include either the `WHERE` clause or `ORDER BY` clause. 3. If you query multiple objects, each object returns up to the minimum number between 2,000/**n** (where **n**=number of objects) and 250. For example, if you query 2 objects, the value of 2,000/2 is higher than 250, so up to 250 results are returned. If you query 10 objects, the value of 2,000/10 is lower than 250, so up to 200 results are returned. 4. Admins (users with the View All Data permission) see the full set of results returned. 5. For all other users, SOSL applies user permission filters. Individual users see only those records that they have access to. Results sets and order vary by the user issuing the search and can change throughout the day as records are added or removed from the index. ![truncation and sharing rules can limit results users see](https://developer.salesforce.com/media/salesforce-soql-sosl/truncation.gif) ## Example Joe Smith, a sales executive at Acme, Inc., wants to find the account record for Industrial Computing. He types Industrial into the search bar. Because so many records match the search term Industrial, a limit is imposed on the results. Unfortunately for Joe, the record he wanted is outside the limit. This concept is illustrated in the image as the single raindrop outside of the filter. Because Joe used a global search, limits are applied to each object type to make up the 2,000 record limit. The illustration shows five blue raindrops going into the filter, but only three make it to the next stage. If Joe limits his search to just one object, the limit applies to only that object, increasing the chance that the record he wants is returned. Joe retries his search by typing Industrial Computing San Francisco. With a more specific search term, the search engine returns better matches, even with the same limits applied. In this scenario, the record Joe’s looking for is one of the blue raindrops that makes it from the top of the filter all the way through to Joe’s search results page. For other SOSL limits, see [SOQL and SOSL Limits](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_soslsoql.htm) in the _Salesforce Developer Limits and Allocations Quick Reference_. # SOSL Syntax A SOSL query begins with the required `FIND` clause. You can then add optional clauses to filter the query by object type, fields, data categories, and more. You can also determine what’s returned. For example, you can specify the order of the results and how many rows to return. After the required `FIND` clause, you can add one or more optional clauses in the following order. ```soql FIND {SearchQuery} [ IN SearchGroup ] [ RETURNING FieldSpec [[ toLabel(fields)] [convertCurrency(Amount)] [FORMAT()]] ] [ WITH DivisionFilter ] [ WITH DATA CATEGORY DataCategorySpec ] [ WITH SNIPPET[(target_length=n)] ] [ WITH NETWORK NetworkIdSpec ] [ WITH PricebookId ] [ WITH METADATA ] [ LIMIT n ] [ UPDATE [TRACKING], [VIEWSTAT] ] ``` **note:** `[OFFSET n](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-offset.md#offset-n)` and `[WHERE](https://developer.salesforce.com/docs/platform/salesforce-soql-sosl/guide/sforce-api-calls-sosl-where.md#where)` are included within `RETURNING FieldSpec`. | Syntax | Description | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `convertCurrency()` | Optional. If an org has multicurrency enabled, converts currency fields to the user’s currency. | | `FIND {SearchQuery}` | Required. Specifies the text (words or phrases) to search for. Enclose the search query with curly braces. If the `SearchQuery` string is longer than 10,000 characters, no result rows are returned. If `SearchQuery` is longer than 4,000 characters, any logical operators are removed. For example, the `AND` operator in a statement with a `SearchQuery` that’s 4,001 characters will default to the `OR` operator, which could return more results than expected. | | `FORMAT()` | Optional. Use `FORMAT` with the `FIND` clause to apply localized formatting to standard and custom number, date, time, and currency fields. The `FORMAT` function supports aliasing. In addition, aliasing is required when the query includes the same field multiple times. | | `IN SearchGroup` | Optional. Scope of fields to search. One of the following values: `ALL FIELDS`, `NAME FIELDS`, `EMAIL FIELDS`, `PHONE FIELDS`, or `SIDEBAR FIELDS`. If unspecified, the default is `ALL FIELDS`. You can specify the list of objects to search in the `RETURNING FieldSpec` clause. | | `LIMIT n` | Optional. Specifies the maximum number of rows to return in the text query, up to 2,000. If unspecified, the default is 2,000, the largest number of rows that can be returned. These limits apply to API version 28.0 and later. Previous versions support a maximum of 200 rows. | | `OFFSET n` | Optional. When expecting many records in a query’s results, you can display the results in multiple pages by using the `OFFSET` clause in a SOSL query. For example, you can use `OFFSET` to display records 51–75 and then jump to displaying records 301–350. Using `OFFSET` is an efficient way to handle large results sets. | | `ORDER BY` | Optional. Specifies the order in which search results are returned using the `ORDER BY` clause. You can also use this clause to display empty records at the beginning or end of the results. | | `RETURNING FieldSpec` | Optional. Information to return in the search result. List of one or more objects and, within each object, list of one or more fields, with optional values to filter against. If unspecified, the search results contain the IDs of all objects found. | | `toLabel(fields)` | Optional. Results from a query are returned translated into the user’s language. | | `USING ListView=` | Optional clause used to search within a single given object’s list view. Only one list view can be specified. Only the first 2,000 records of the list view are searched, according to the sort order the user has set for the list view. | | `[ UPDATE [TRACKING \| VIEWSTAT][,...] ]` | Optional. If an org uses Salesforce Knowledge: `UPDATE TRACKING` tracks keywords used in Salesforce Knowledge article search; `Update an Article’s Viewstat with SOSL` updates an article’s view statistics; and `UPDATE TRACKING, VIEWSTAT` does both. | | `WHERE` | Optional. By default, a SOSL query on an object retrieves all rows that are visible to the user. To limit the search, filter the search result by specific field values. | | `WITH DATA CATEGORY DataCategorySpec` | Optional. If an org uses Salesforce Knowledge articles or answers, filters all search results based on one or more data categories. | | `WITH DivisionFilter` | Optional. If an org uses divisions, filters all search results based on values for the `Division` field. | | `WITH HIGHLIGHT` | Optional. In search results for certain objects, highlights the terms matching the search query. | | `WITH METADATA = MetadataSpec` | Optional. Specifies if metadata is returned in the response. The default setting is no, meaning no metadata is returned. | | `WITH NETWORK NetworkIdSpec` | Optional. Filters search results by community ID. | | `WITH PricebookId` | Optional. Filters product search results by a single price book ID. | | `WITH SNIPPET [(target_length=n)]` | Optional. If an org uses Salesforce Knowledge articles, displays contextual snippets and highlights the search term for each article in the search results. By default, each snippet displays up to about 300 characters. Add the optional `target_length` parameter to specify an alternate target length, which can be from 100 and 500 characters. | | `WITH SPELL_CORRECTION` | Optional. When set to `true`, spell correction is enabled for searches that support spell correction. When set to `false`, spell correction isn’t enabled. The default value is `true`. | **Note:** This clause doesn’t apply to articles, documents, feed comments, feed items, files, products, and solutions. If these objects are specified in the RETURNING clause, the search is not limited to specific fields, and all fields are searched. **Note:** The RETURNING clause is required (not optional) for SOSL executed in Apex. **note:** The SOSL statement character limit is tied to the SOQL statement character limit defined for your org. By default, SOQL and SOSL queries can’t exceed 100,000 characters. For SOSL statements that exceed this maximum length, the API returns a `MALFORMED_SEARCH` exception code, and no result rows are returned. # source Context Variable Pass in any context and get it back in the callback method by using the `source` context variable. For an example of how to use `source` in an error handling context, see [Error Handling with the AJAX Toolkit](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-errors.md). # Specifying all Components of a Type **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. To retrieve all components of a particular type, use the wildcard symbol (\*). For example, to retrieve all custom objects: ```xml * CustomObject 68.0 ``` The wildcard symbol does not apply to all metadata types. For example, using the wildcard with the `CustomObject` type name will not retrieve standard objects. To retrieve a standard object, you must explicitly name the object in package.xml. Likewise, if you want to retrieve custom fields defined on standard objects, you must name the object and field. # Specifying Named Components **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported.  If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. To retrieve a component, specify the type of component in the `` element and declare each component to be retrieved or deployed in the `` element. The following is a sample package.xml project manifest that names two custom objects to be retrieved or deployed: ```xml MyCustomObject__c MyHelloWorldObject__c CustomObject 68.0 ``` Some metadata components are sub-components of another component. This means you must dot-qualify the sub-component with the parent component name. The following metadata components are defined as part of an object: - `CustomField` - `Picklist` - `RecordType` - `Weblink` - `ValidationRule` For example, the following code retrieves a validation rule called `ValidationRuleName` on the Opportunity object: ```xml Opportunity.ValidationRuleName ValidationRule 68.0 ``` # Specifying Standard Objects **note:** The Ant Migration Tool is retired with Spring ’24. The tool continues to function as-is for future API versions but isn’t updated with new functionality and isn’t supported. If Salesforce adds a new feature that is incompatible with Ant, the Ant Migration Tool won't be updated to support it. To manage metadata changes, switch to Salesforce CLI for a modern, supported developer experience. To retrieve standard objects and/or custom fields on standard objects, you must name the component in package.xml. The following package.xml file will retrieve a single field `EngineeringReqNumber__c`, on the Case object, as well as the entire Account object. ```xml Case.EngineeringReqNumber__c CustomField Account CustomObject 68.0 ``` **note:** Custom objects and standard objects should be specified in the same `` section, the one containing `CustomObject`. # Speech to Text Action Converts speech in an audio file to text using AI-powered speech recognition. This action is available in API version 66.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v66.0/actions/standard/speechToText` **Formats:** JSON, XML **HTTP Methods:** POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`contentDocumentId`|string|Required. The ID of the audio file stored in Salesforce Files. This value is the contentDocumentId from the ContentDocument object that represents the file to be transcribed.| |`transcriptionModel`|string|Optional. The transcription model used to convert speech to text. Valid values are `whisper-v3-turbo` and `elevenlabs-scribe-v2`. If you don't specify a value, `whisper-v3-turbo` is used.| ## Outputs |Output|Type|Description| |------|----|-----------| |`convertedText`| |The transcript of the audio file, returned as plain text in the detected language.| ## Usage **Sample Input** This sample uses `elevenlabs-scribe-v2`. You can also set `transcriptionModel` to `whisper-v3-turbo`, which is the default if the value isn't specified. ```apex { "inputs": [ { "contentDocumentId": "069xx000004WhFoAAK", "transcriptionModel": "elevenlabs-scribe-v2" } ] } ``` **Sample Output** ```apex { "outputs": [ { "convertedText": "Thank you for contacting support. How can I help you today?" } ] } ``` # Spring Framework The Spring Framework allows you to use XML files to configure beans. Each bean represents an instance of an object; the parameters correspond to each object's setter methods. |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. **note:** The Data Loader configuration files are based on the [Spring Framework](http://www.springframework.org/), which is an open-source, full-stack Java/J2EE application framework. A typical bean has these attributes. - class—Specifies the implementation class for the bean instance. - id—Uniquely identifies the bean to `XmlBeanFactory`, which is the class that gets objects from an XML configuration file. For more information on the Spring Framework, see [the official documentation](http://www.springframework.org/documentation) and the [support forums](http://forum.springsource.org/). Note that Salesforce cannot guarantee the availability or accuracy of external websites. # SQL Configuration When running Data Loader in batch mode from the command line, the `SqlConfig` class contains configuration parameters for accessing specific data in the database. |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. As shown in these code samples, queries and inserts are different but very similar. The bean must be of type `com.salesforce.dataloader.dao.database.SqlConfig` and have these properties. - `sqlString` The SQL code to be used by the data access object. The SQL can contain replacement parameters that make the string dependent on configuration or operation variables. Replacement parameters must be delimited on both sides by “@” characters. For example, `@process.lastRunDate@`. - `sqlParams` A property of type `map` that contains descriptions of the replacement parameters specified in `sqlString`. Each entry represents one replacement parameter: the key is the replacement parameter's name, the value is the fully qualified Java type to be used when the parameter is set on the SQL statement. Note that “java.sql” types are sometimes required, such as `java.sql.Date` instead of `java.util.Date`. For more information, see [the official JDBC API documentation](http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/). - `columnNames` Used when queries (`SELECT` statements) return a JDBC `ResultSet`. Contains column names for the data outputted by executing the SQL. The column names are used to access and return the output to the caller of the `DataReader` interface. ## SQL Query Bean Example ```xml SELECT distinct '012x00000000Ij7' recordTypeId, accounts.account_number, org.organization_name, concat (concat(parties.address1, ' '), parties.address2) billing_address, locs.city, locs.postal_code, locs.state, locs.country, parties.sic_code from ar.hz_cust_accounts accounts, ar.hz_organization_profiles org, ar.hz_parties parties, ar.hz_party_sites party_sites, ar.hz_locations locs where accounts.PARTY_ID = org.PARTY_ID and parties.PARTY_ID = accounts.PARTY_ID and party_sites.PARTY_ID = accounts.PARTY_ID and locs.LOCATION_ID = party_sites.LOCATION_ID and (locs.last_update_date > @process.lastRunDate@ OR accounts.last_update_date > @process.lastRunDate@ recordTypeId account_number organization_name billing_address city postal_code state country sic_code ``` ## SQL Insert Bean Example ```xml INSERT INTO REP.INT_PARTIES ( BILLING_ADDRESS, SIC_CODE) VALUES (@billing_address@, @sic_code@) ``` # SrcPredJobStatusChgEvent Notifies subscribers that the Data Cloud prediction job’s status is changed. This object is available in API version 50.0 and later. ## Supported Calls `describeSObjects()` ## Supported Subscribers |Subscriber|Supported?| |----------|----------| |Apex Triggers|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Flows|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Processes|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Pub/Sub API|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| |Streaming API (CometD)|![Yes](https://developer.salesforce.com/media/platform-events/checkmark_16.png)| ## Subscription Channel `/event/srcpredjobstatuschgevent` ## Event Delivery Allocation Enforced Yes ## Fields ### `ErrorCode` **Type:** string **Properties:** Nillable **Description:** If the event’s status is an error, contains the error code. ### `EventCreationDate` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the event occurred. ### `EventPublishDate` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the event published. ### `EventType` **Type:** string **Properties:** Nillable **Description:** The type of event that occurred. ### `EventUuid` **Type:** string **Properties:** Nillable **Description:** A universally unique identifier (UUID) that identifies a platform event message. ### `LastRefreshDate` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the prediction job was last changed. ### `LastRunStatus` **Type:** string **Properties:** Nillable **Description:** The status of the prediction job’s last run. ### `LastRunTime` **Type:** dateTime **Properties:** Nillable **Description:** The date and time when the prediction job was last run. ### `OutputDloName` **Type:** string **Properties:** Nillable **Description:** The developer name of the DLO containing the prediction job’s output. ### `PredictionApiName` **Type:** string **Properties:** Nillable **Description:** The API name of the prediction job. ### `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. ### `RowsProcessed` **Type:** long **Properties:** Nillable **Description:** The number of rows processed during the prediction. ### `RowsUpdated` **Type:** long **Properties:** Nillable **Description:** The number of rows updated during the prediction. ### `SchemaVersion` **Type:** string **Properties:** Nillable **Description:** The version of the event schema. # Standard Actions and Overrides Basics There are six standard actions available on most standard and all custom objects: Tab, List, View, Edit, New, and Delete. In Salesforce Classic, these are all distinct actions. Lightning Experience and the Salesforce mobile app combine the Tab and List actions into one action, Object Home. However, Object Home is reached via the Tab action in Lightning Experience, and the List action in the Salesforce mobile app. Finally, the Salesforce mobile app has a unique Search action (reached via Tab). (Yes, it’s a bit awkward and complicated.) ## Names in Setup for Actions You an Override This table lists the standard actions you can override for an object as the actions are named in Setup, and the resulting action that’s overridden in the three different user experiences. |Override in Setup|Salesforce Classic|Lightning Experience|Mobile| |-----------------|------------------|--------------------|------| |Tab|object tab|object home|search| |List|object list|**n/a**|object home| |View|record view|record home|record home| |Edit|record edit|record edit|record edit| |New|record create|record create|record create| |Delete|record delete|record delete|record delete| **note:** - “n/a” doesn’t mean you can’t *access* the standard behavior, and it doesn’t mean you can’t *override* the standard behavior. It means you can’t *access the override*. It’s the override’s functionality that’s not available. - There are two additional standard actions, Accept and Clone. These actions are more complex, and overriding them is an advanced project. Overriding them isn’t supported. ## How and Where You Can Use Action Overrides Aura components can be used to override the View, New, New Event, Edit, and Tab standard actions in Lightning Experience and the Salesforce mobile app. You can use an Aura component as an override in Lightning Experience and mobile, but not Salesforce Classic. # Standard and Custom Object Types An attribute can have a type corresponding to a standard or custom object. For example, this is an attribute for a standard `Account` object: ```nolang ``` This is an attribute for an `Expense__c` custom object: ```nolang ``` **See Also** - [Using Apex to Work with Salesforce Records](https://developer.salesforce.com/docs/platform/aura-platform/apex/apex-records.md) # Standard Controllers A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a page, and can modify component behavior. The Lightning platform provides a number of standard controllers that contain the same functionality and logic that are used for standard Salesforce pages. For example, if you use the standard Accounts controller, clicking a **Save** button in a Visualforce page results in the same behavior as clicking **Save** on a standard Account edit page. A standard controller exists for every Salesforce object that can be queried using the Lightning Platform API. - **[Associating a Standard Controller with a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-associate.md)** - **[Accessing Data with a Standard Controller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-access-data.md)** - **[Using Standard Controller Actions](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-actions.md)** - **[Validation Rules and Standard Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-validation-rules.md)** - **[Styling Pages that Use Standard Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-styling.md)** - **[Checking for Object Accessibility](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-std-checking-accessibility.md)** If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object is inaccessible. To avoid this error, ensure that your Visualforce components only render if a user has access to the object associated with the controller. # Standard Design Tokens for Experience Builder Sites Use a subset of the standard design tokens to make your components compatible with the Theme panel in Experience Builder. The Theme panel enables administrators to quickly style an entire site using these properties. Each property in the Theme panel maps to one or more standard design tokens. When an administrator updates a property in the Theme panel, the system automatically updates any Lightning components that use the tokens associated with that branding property. **important:** Salesforce recommends that you use [Styling Hooks](https://www.lightningdesignsystem.com/platforms/lightning/styling-hooks/) instead of design tokens if possible. While existing design tokens still work, styling hooks are the future of customization for Lightning web components and Aura components. See [Replace Design Tokens with Styling Hooks](https://developer.salesforce.com/docs/platform/aura-platform/guide/styling-hooks.md). ![Experience Builder Theme panel](https://developer.salesforce.com/media/aura-platform/design_tokens_community_builder.png) ## Available Tokens for Experience Builder Sites For Experience Builder sites, these standard tokens are available when extending from [`forceCommunity:base`](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-standard-force-base.md#standard-design-tokens-forcebase). **important:** The standard token values evolve along with SLDS. Available tokens and their values can change without notice. **important:** Design tokens are not available for navigation branding properties. To add branding to navigation properties, override the navigation bar within the custom components. See [CSS Overrides Migration for the Navigation Menu](https://developer.salesforce.com/docs/atlas.en-us.communities_dev.meta/communities_dev/communities_dev_nav_menu_css.htm). | These Branding panel properties... | ...map to these standard design tokens | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Text Color | `colorTextDefault` | | Detail Text Color | `colorTextActionLabel`, `colorTextLabel`, `colorTextPlaceholder`, or `colorTextWeak` | | Action Color | `colorBackgroundButtonBrand`, `colorBorderBrand`, `colorBorderButtonBrand`, `colorBrand`, `colorTextBrand`, `colorTextTabLabelSelected`, or `colorTextActionLabelActive` | | Link Color | `colorTextLink` | | Overlay Text Color | `colorTextButtonBrand`, `colorTextButtonBrandHover`, or `colorTextInverse` | | Border Color | `colorBorder`, `colorBorderButtonDefault`, `colorBorderInput`, or `colorBorderSeparatorAlt` | | Company Logo | `brandLogoImage` | | Header Image | `headerImageUrl` | | Login Pages Background Image | `LoginBackgroundImage` | | Primary Font | `fontFamily` | | Text Case | `textTransform` | **note:** As of Summer ’18 `colorBackgroundHighlight` is no longer mapped to Action Color. In addition, the following standard tokens are available for derived theme properties in the template. You can indirectly access derived properties when you update the properties in the Theme panel. For example, if you change the Action Color property in the Theme panel, the system automatically recalculates the Action Color Darker value based on the new value. | These derived branding properties... | ...map to these standard design tokens | | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | Action Color Darker (Derived from Action Color) | `colorBackgroundButtonBrandActive` or `colorBackgroundButtonBrandHover` | | Hover Color (Derived from Action Color) | `colorBackgroundButtonDefaultHover`, `colorBackgroundRowHover`, `colorBackgroundRowSelected`, or `colorBackgroundShade` | | Link Color Darker (Derived from Link Color) | `colorTextLinkActive` or `colorTextLinkHover` | For a complete list of the design tokens available in the SLDS, see [Design Tokens](http://www.lightningdesignsystem.com/resources/tokens/) on the Lightning Design System site. **See Also** - [Configure Components for Experience Builder](https://developer.salesforce.com/docs/platform/aura-platform/components/components-config-for-builder.md) # Standard Design Tokens— force:base The standard tokens available are a subset of the design tokens offered in the Salesforce Lightning Design System (SLDS). The following tokens are available when extending from `force:base`. **important:** Salesforce recommends that you use [Styling Hooks](https://www.lightningdesignsystem.com/platforms/lightning/styling-hooks/) instead of design tokens if possible. While existing design tokens still work, styling hooks are the future of customization for Lightning web components and Aura components. See [Replace Design Tokens with Styling Hooks](https://developer.salesforce.com/docs/platform/aura-platform/guide/styling-hooks.md). ## Available Tokens **important:** The standard token values evolve along with SLDS. Available tokens and their values can change without notice. Token values presented here are for example only. |Token Name|Example Value| |----------|-------------| |`borderWidthThin`|1px| |`borderWidthThick`|2px| |`spacingXxxSmall`|0.125rem| |`spacingXxSmall`|0.25rem| |`spacingXSmall`|0.5rem| |`spacingSmall`|0.75rem| |`spacingMedium`|1rem| |`spacingLarge`|1.5rem| |`spacingXLarge`|2rem| |`varSpacingXxSmall`|0.25rem| |`varSpacingXSmall`|0.5rem| |`varSpacingSmall`|0.75rem| |`varSpacingMedium`|1rem| |`varSpacingLarge`|1.5rem| |`varSpacingXLarge`|2rem| |`varSpacingXxLarge`|3rem| |`varSpacingVerticalXxSmall`|0.25rem| |`varSpacingVerticalXSmall`|0.5rem| |`varSpacingVerticalSmall`|0.75rem| |`varSpacingVerticalMedium`|1rem| |`varSpacingVerticalLarge`|1.5rem| |`varSpacingVerticalXLarge`|2rem| |`varSpacingVerticalXxLarge`|3rem| |`varSpacingHorizontalXxSmall`|0.25rem| |`varSpacingHorizontalXSmall`|0.5rem| |`varSpacingHorizontalSmall`|0.75rem| |`varSpacingHorizontalMedium`|1rem| |`varSpacingHorizontalLarge`|1.5rem| |`varSpacingHorizontalXLarge`|2rem| |`varSpacingHorizontalXxLarge`|3rem| |`sizeXxSmall`|6rem| |`sizeXSmall`|12rem| |`sizeSmall`|15rem| |`sizeMedium`|20rem| |`sizeLarge`|25rem| |`sizeXLarge`|40rem| |`sizeXxLarge`|60rem| |`squareIconUtilitySmall`|1rem| |`squareIconUtilityMedium`|1.25rem| |`squareIconUtilityLarge`|1.5rem| |`squareIconLargeBoundary`|3rem| |`squareIconLargeBoundaryAlt`|5rem| |`squareIconLargeContent`|2rem| |`squareIconMediumBoundary`|2rem| |`squareIconMediumBoundaryAlt`|2.25rem| |`squareIconMediumContent`|1rem| |`squareIconSmallBoundary`|1.5rem| |`squareIconSmallContent`|.75rem| |`squareIconXSmallBoundary`|1.25rem| |`squareIconXSmallContent`|.5rem| |`fontWeightLight`|300| |`fontWeightRegular`|400| |`fontWeightBold`|700| |`lineHeightHeading`|1.25| |`lineHeightText`|1.375| |`lineHeightReset`|1| |`lineHeightTab`|2.5rem| |`fontFamily`|'Salesforce Sans', Arial, sans-serif| |`borderRadiusSmall`|.125rem| |`borderRadiusMedium`|.25rem| |`borderRadiusLarge`|.5rem| |`borderRadiusPill`|15rem| |`borderRadiusCircle`|50%| |`colorBorder`|rgb(216, 221, 230)| |`colorBorderBrand`|rgb(21, 137, 238)| |`colorBorderError`|rgb(194, 57, 52)| |`colorBorderSuccess`|rgb(75, 202, 129)| |`colorBorderWarning`|rgb(255, 183, 93)| |`colorBorderTabSelected`|rgb(0, 112, 210)| |`colorBorderSeparator`|rgb(244, 246, 249)| |`colorBorderSeparatorAlt`|rgb(216, 221, 230)| |`colorBorderSeparatorInverse`|rgb(42, 66, 108)| |`colorBorderRowSelected`|rgb(0, 112, 210)| |`colorBorderRowSelectedHover`|rgb(21, 137, 238)| |`colorBorderButtonBrand`|rgb(0, 112, 210)| |`colorBorderButtonBrandDisabled`|rgba(0, 0, 0, 0)| |`colorBorderButtonDefault`|rgb(216, 221, 230)| |`colorBorderButtonInverseDisabled`|rgba(255, 255, 255, 0.15)| |`colorBorderInput`|rgb(216, 221, 230)| |`colorBorderInputActive`|rgb(21, 137, 238)| |`colorBorderInputDisabled`|rgb(168, 183, 199)| |`colorBorderInputCheckboxSelectedCheckmark`|rgb(255, 255, 255)| |`colorBackground`|rgb(244, 246, 249)| |`colorBackgroundAlt`|rgb(255, 255, 255)| |`colorBackgroundAltInverse`|rgb(22, 50, 92)| |`colorBackgroundRowHover`|rgb(244, 246, 249)| |`colorBackgroundRowActive`|rgb(238, 241, 246)| |`colorBackgroundRowSelected`|rgb(240, 248, 252)| |`colorBackgroundRowNew`|rgb(217, 255, 223)| |`colorBackgroundInverse`|rgb(6, 28, 63)| |`colorBackgroundBrowser`|rgb(84, 105, 141)| |`colorBackgroundChromeMobile`|rgb(0, 112, 210)| |`colorBackgroundChromeDesktop`|rgb(255, 255, 255)| |`colorBackgroundHighlight`|rgb(250, 255, 189)| |`colorBackgroundModal`|rgb(255, 255, 255)| |`colorBackgroundModalBrand`|rgb(0, 112, 210)| |`colorBackgroundNotificationBadge`|rgb(194, 57, 52)| |`colorBackgroundNotificationBadgeHover`|rgb(0, 95, 178)| |`colorBackgroundNotificationBadgeFocus`|rgb(0, 95, 178)| |`colorBackgroundNotificationBadgeActive`|rgb(0, 57, 107)| |`colorBackgroundNotificationNew`|rgb(240, 248, 252)| |`colorBackgroundPayload`|rgb(244, 246, 249)| |`colorBackgroundShade`|rgb(224, 229, 238)| |`colorBackgroundStencil`|rgb(238, 241, 246)| |`colorBackgroundStencilAlt`|rgb(224, 229, 238)| |`colorBackgroundScrollbar`|rgb(224, 229, 238)| |`colorBackgroundScrollbarTrack`|rgb(168, 183, 199)| |`colorBrand`|rgb(21, 137, 238)| |`colorBrandDark`|rgb(0, 112, 210)| |`colorBackgroundModalButton`|rgba(0, 0, 0, 0.07)| |`colorBackgroundModalButtonActive`|rgba(0, 0, 0, 0.16)| |`colorBackgroundInput`|rgb(255, 255, 255)| |`colorBackgroundInputActive`|rgb(255, 255, 255)| |`colorBackgroundInputCheckbox`|rgb(255, 255, 255)| |`colorBackgroundInputCheckboxDisabled`|rgb(216, 221, 230)| |`colorBackgroundInputCheckboxSelected`|rgb(21, 137, 238)| |`colorBackgroundInputDisabled`|rgb(224, 229, 238)| |`colorBackgroundInputError`|rgb(255, 221, 225)| |`colorBackgroundPill`|rgb(255, 255, 255)| |`colorBackgroundToast`|rgba(84, 105, 141, 0.95)| |`colorBackgroundToastSuccess`|rgb(4, 132, 75)| |`colorBackgroundToastError`|rgba(194, 57, 52, 0.95)| |`shadowDrag`|0 2px 4px 0 rgba(0, 0, 0, 0.40)| |`shadowDropDown`|0 2px 3px 0 rgba(0, 0, 0, 0.16)| |`shadowHeader`|0 2px 4px rgba(0, 0, 0, 0.07)| |`shadowButtonFocus`|0 0 3px #0070D2| |`shadowButtonFocusInverse`|0 0 3px #E0E5EE| |`colorTextActionLabel`|rgb(84, 105, 141)| |`colorTextActionLabelActive`|rgb(22, 50, 92)| |`colorTextBrand`|rgb(21, 137, 238)| |`colorTextBrowser`|rgb(255, 255, 255)| |`colorTextBrowserActive`|rgba(0, 0, 0, 0.4)| |`colorTextDefault`|rgb(22, 50, 92)| |`colorTextError`|rgb(194, 57, 52)| |`colorTextInputDisabled`|rgb(84, 105, 141)| |`colorTextInputFocusInverse`|rgb(22, 50, 92)| |`colorTextInputIcon`|rgb(159, 170, 181)| |`colorTextInverse`|rgb(255, 255, 255)| |`colorTextInverseWeak`|rgb(159, 170, 181)| |`colorTextInverseActive`|rgb(94, 180, 255)| |`colorTextInverseHover`|rgb(159, 170, 181)| |`colorTextLink`|rgb(0, 112, 210)| |`colorTextLinkActive`|rgb(0, 57, 107)| |`colorTextLinkDisabled`|rgb(22, 50, 92)| |`colorTextLinkFocus`|rgb(0, 95, 178)| |`colorTextLinkHover`|rgb(0, 95, 178)| |`colorTextLinkInverse`|rgb(255, 255, 255)| |`colorTextLinkInverseHover`|rgba(255, 255, 255, 0.75)| |`colorTextLinkInverseActive`|rgba(255, 255, 255, 0.5)| |`colorTextLinkInverseDisabled`|rgba(255, 255, 255, 0.15)| |`colorTextModal`|rgb(255, 255, 255)| |`colorTextModalButton`|rgb(84, 105, 141)| |`colorTextStageLeft`|rgb(224, 229, 238)| |`colorTextTabLabel`|rgb(22, 50, 92)| |`colorTextTabLabelSelected`|rgb(0, 112, 210)| |`colorTextTabLabelHover`|rgb(0, 95, 178)| |`colorTextTabLabelFocus`|rgb(0, 95, 178)| |`colorTextTabLabelActive`|rgb(0, 57, 107)| |`colorTextTabLabelDisabled`|rgb(224, 229, 238)| |`colorTextToast`|rgb(224, 229, 238)| |`colorTextWeak`|rgb(84, 105, 141)| |`colorTextIconBrand`|rgb(0, 112, 210)| |`colorTextButtonBrand`|rgb(255, 255, 255)| |`colorTextButtonBrandHover`|rgb(255, 255, 255)| |`colorTextButtonBrandActive`|rgb(255, 255, 255)| |`colorTextButtonBrandDisabled`|rgb(255, 255, 255)| |`colorTextButtonDefault`|rgb(0, 112, 210)| |`colorTextButtonDefaultHover`|rgb(0, 112, 210)| |`colorTextButtonDefaultActive`|rgb(0, 112, 210)| |`colorTextButtonDefaultDisabled`|rgb(216, 221, 230)| |`colorTextButtonDefaultHint`|rgb(159, 170, 181)| |`colorTextButtonInverse`|rgb(224, 229, 238)| |`colorTextButtonInverseDisabled`|rgba(255, 255, 255, 0.15)| |`colorTextIconDefault`|rgb(84, 105, 141)| |`colorTextIconDefaultHint`|rgb(159, 170, 181)| |`colorTextIconDefaultHover`|rgb(0, 112, 210)| |`colorTextIconDefaultActive`|rgb(0, 57, 107)| |`colorTextIconDefaultDisabled`|rgb(216, 221, 230)| |`colorTextIconInverse`|rgb(255, 255, 255)| |`colorTextIconInverseHover`|rgb(255, 255, 255)| |`colorTextIconInverseActive`|rgb(255, 255, 255)| |`colorTextIconInverseDisabled`|rgba(255, 255, 255, 0.15)| |`colorTextLabel`|rgb(84, 105, 141)| |`colorTextPlaceholder`|rgb(84, 105, 141)| |`colorTextPlaceholderInverse`|rgb(224, 229, 238)| |`colorTextRequired`|rgb(194, 57, 52)| |`colorTextPill`|rgb(0, 112, 210)| |`durationInstantly`|0s| |`durationImmediately`|0.05s| |`durationQuickly`|0.1s| |`durationPromptly`|0.2s| |`durationSlowly`|0.4s| |`durationPaused`|3.2s| |`colorBackgroundButtonBrand`|rgb(0, 112, 210)| |`colorBackgroundButtonBrandActive`|rgb(0, 57, 107)| |`colorBackgroundButtonBrandHover`|rgb(0, 95, 178)| |`colorBackgroundButtonBrandDisabled`|rgb(224, 229, 238)| |`colorBackgroundButtonDefault`|rgb(255, 255, 255)| |`colorBackgroundButtonDefaultHover`|rgb(244, 246, 249)| |`colorBackgroundButtonDefaultFocus`|rgb(244, 246, 249)| |`colorBackgroundButtonDefaultActive`|rgb(238, 241, 246)| |`colorBackgroundButtonDefaultDisabled`|rgb(255, 255, 255)| |`colorBackgroundButtonIcon`|rgba(0, 0, 0, 0)| |`colorBackgroundButtonIconHover`|rgb(244, 246, 249)| |`colorBackgroundButtonIconFocus`|rgb(244, 246, 249)| |`colorBackgroundButtonIconActive`|rgb(238, 241, 246)| |`colorBackgroundButtonIconDisabled`|rgb(255, 255, 255)| |`colorBackgroundButtonInverse`|rgba(0, 0, 0, 0)| |`colorBackgroundButtonInverseActive`|rgba(0, 0, 0, 0.24)| |`colorBackgroundButtonInverseDisabled`|rgba(0, 0, 0, 0)| |`lineHeightButton`|1.875rem| |`lineHeightButtonSmall`|1.75rem| |`colorBackgroundAnchor`|rgb(244, 246, 249)| For a complete list of the design tokens available in the SLDS, see [Design Tokens](https://www.lightningdesignsystem.com/design-tokens/) on the Lightning Design System site. **See Also** - [Extending Tokens Bundles](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-extending.md) # Standard List Controller Actions Standard list controllers support action methods. Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button or hovers over an area of the page. Call action methods from page markup by using `{! }` notation in the `action` attribute of one of these tags. - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-commandbutton.md) creates a button that calls an action - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-commandlink.md) creates a link that calls an action - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-actionpoller.md) periodically calls an action - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-actionsupport.md) makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-actionfunction.md) defines a new JavaScript function that calls an action - [``](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/components/pages-compref-page.md) calls an action when the page is loaded This table describes the action methods all standard list controllers support. You can associate these actions with any Visualforce component that includes an `action` attribute. |Action|Description| |------|-----------| |`save`|Inserts new records or updates existing records that have been changed. After this operation is finished, the `save` action returns the user to the original page, if known, or to the home page.| |`quicksave`|Inserts new records or updates existing records that have been changed. Unlike the `save` action, `quicksave` doesn’t redirect the user to another page.| |`list`|Returns a PageReference object of the standard list page, based on the most recently used list filter for that object when the `filterId` isn’t specified by the user.| |`cancel`|Aborts an edit operation. After this operation is finished, the `cancel` action returns the user to the page where they originally invoked the edit.| |`first`|Displays the first page of records in the set.| |`last`|Displays the last page of records in the set.| |`next`|Displays the next page of records in the set.| |`previous`|Displays the previous page of records in the set.| In this example, the user specifies a filter to view account records. ```markup ``` The page is associated with the standard Account list controller, which is based on the `StandardSetController` Apex class. The `{!listviewoptions}` expression calls the `getListViewOptions()` method for `StandardSetController` and evaluates to the available list views. The list view that the user selects is bound to the `filterId` property of the controller. When the `filterId` changes, the records available to the page change according to the filter. So when the user clicks **Go**, the standard list page displays the selected filtered records. # Standard List Controllers Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce pages that work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with the following objects: - Account - Asset - Campaign - Case - Contact - Contract - Idea - Lead - Opportunity - Order - Product2 - Solution - User - Custom objects - **[Associating a Standard List Controller with a Visualforce Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-associate.md)** - **[Accessing Data with List Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-access-data.md)** - **[Standard List Controller Actions](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-actions.md)** Standard list controllers support action methods. Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button or hovers over an area of the page. - **[Pagination with a List Controller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-pagination.md)** To add pagination to a Visualforce page that has a list controller, use the `next` and `previous` actions. - **[List Views with Standard List Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-list-views.md)** To display a filtered list of records on a Visualforce page, associate the page with a standard list controller. - **[Editing Records with List Controllers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-sosc-edit-data.md)** **See Also** - [Build a Custom Controller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/controller/pages-controller-custom.md) # Standard Object Notes Learn about the characteristics of change events for some standard objects and the fields included in the event messages. - **[Change Events for Tasks and Events](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-standard-objects-task-event.md)** You can receive change events for single and recurring tasks and calendar events, including events with invitees. - **[Change Events for Person Accounts](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-standard-objects-person-account.md)** Because a person account record combines fields from an account and a contact, changing a person account results in two change events: one for the account and one for the contact, provided that both objects are selected for change data capture. The two change events are generated for all changes to a person account, including create, update, delete, and undelete operations. - **[Change Events for Users](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-standard-objects-user.md)** The user and email preferences in change events include only the preferences that are enabled (set to true) without their Boolean values. Preferences that are disabled (set to false) are not included in the event payload. - **[Change Events for Lead Conversion](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-standard-objects-lead-conversion.md)** Converting a lead results in the creation of an account, a contact, and optionally an opportunity, and also a lead update. When converting a lead, the change event for the lead update includes fields specific to the conversion. - **[Change Events for PricebookEntry](https://developer.salesforce.com/docs/platform/change-data-capture/guide/cdc-standard-objects-pricebookentry.md)** The Create Change Events payload does not include the system fields (sCreatedById, CreatedDate, LastModifiedById, and LastModifiedDate). This is due to the highly customized nature of the PricebookEntry object, which prevents these specific fields from being captured at the time the event is generated. # Standard Platform Event Object List Salesforce publishes standard platform events in response to an action that occurred in the org or to report errors. For example, LoginEventStream monitors user login activity and BatchApexErrorEvent reports errors encountered in batch Apex jobs. You can subscribe to a standard platform event using the subscription mechanism that the event supports. - **[AcademicTermGpaCalcEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-academictermgpacalcevent.md)** 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. - **[AcadRgstrApplnEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-acadrgstrapplnevent.md)** 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. - **[AcadRgstrEligCritRunEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-acadrgstreligcritrunevent.md)** 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. - **[AgentQltyEvalEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-agentqltyevalevent.md)** Notifies subscribers of quality evaluations for agents that occur during voice calls, messaging sessions, and case interactions. This object is available in API version 68.0 and later. - **[AiJobRunStatusEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-aijobrunstatusevent.md)** Notifies subscribers when an `AiJobRun` object changes status to `InProgress`, `Completed`, or `Failed`. This object is available in API version 65.0 and later. - **[AIPredictionEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-aipredictionevent.md)** Notifies subscribers when an Einstein feature, such as Prediction Builder or Case Classification, has written prediction results back to a target object and AI prediction field. This object is available in API version 46.0 and later. - **[AIUpdateRecordEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-aiupdaterecordevent.md)** Notifies subscribers when Einstein Case Classification has generated a case field value prediction and potentially updated a case record. This object is available in API version 47.0 and later. - **[AppointmentSchedulingEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-appointmentschedulingevent.md)** Notifies subscribers when an appointment schedule is added, updated, or deleted. This object is available in API version 50.0 and later. - **[AsgnRsrcApptSchdEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-asgnrsrcapptschdevent.md)** Represents the assigned resources that are part of various platform events. This object is included in a streamed notification received on the channels for the parent platform events. You can’t subscribe to the AsgnRsrcApptSchdEvent channel directly. This object is available in API version 50.0 and later. - **[SvcApptSchdEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-svcapptschdevent.md)** Represents the service appointment event. This object is included in a streamed notification received on the channels for the parent platform events. You can’t subscribe to the SvcApptSchdEvent channel directly. This object is available in API version 50.0 and later. - **[AppvlWorkItemNtfcnEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-appvlworkitemntfcnevent.md)** Tracks the asynchronous management of notification systems in Advanced Approvals. This object is available in API version 66.0 and later. - **[AssetAmendInitiatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetamendinitiatedevent.md)** Notifies subscribers when the process started by the `/asset-management/assets/collection/actions/initiate-amend-quantity` REST request is complete. If the process is successful, use this event to learn about the amendment order that was created. If the process isn't successful, use the RevenueTransactionErrorLog records to learn about the errors and how to fix them. This object is available in API version 56.0 and later. - **[AssetAmendErrorDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetamenderrordtlevent.md)** Contains information about errors that occurred during the processing of an `/asset-management/assets/collection/actions/initiate-amend-quantity` request. This object is included in an `AssetAmendInitiatedEvent` message. You can’t subscribe to `AssetAmendErrorDtlEvent` directly. This object is available in API version 56.0 only. - **[AssetCancelInitiatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetcancelinitiatedevent.md)** Notifies subscribers when the process started by the `/asset-management/assets/collection/actions/initiate-cancellation` process is complete. If the process is successful, use this event to learn about the cancellation order that was created. If the process isn't successful, use the RevenueTransactionErrorLog records to learn about the errors and how to fix them. This object is available in API version 55.0 and later. - **[AssetCancelErrorDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetcancelerrordtlevent.md)** Contains information about errors that occurred during the processing of an `/asset-management/assets/collection/actions/initiate-cancellation` request. This object is included in an `AssetCancelInitiatedEvent` message. You can't subscribe to `AssetCancelErrorDtlEvent` directly. This object is available in API versions 55.0 and 56.0 only. - **[AssetRenewInitiatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetrenewinitiatedevent.md)** Notifies subscribers when the process started by the `/asset-management/assets/collection/actions/initiate-renew` REST request is complete. If the process is successful, use this event to learn about the renewal order that was created. If the process isn't successful, use the RevenueTransactionErrorLog records to learn about the errors and how to fix them. This object is available in API version 55.0 and later. - **[AssetRenewErrorDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assetrenewerrordtlevent.md)** Contains information about errors that occurred during the processing of an `/asset-management/assets/collection/actions/initiate-renew` request. This object is included in an `AssetRenewInitiatedEvent` message. You can't subscribe to `AssetRenewErrorDtlEvent` directly. This object is available in API versions 55.0 and 56.0 only. - **[AssetTokenEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-assettokenevent.md)** Notifies subscribers of asset token issuance and registration of a connected device as an Asset. This object is available in API version 39.0 and later. - **[AsyncThirdPartyPaymentGatewayEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-asyncthirdpartypaymentgatewayevent.md)** Represents an asynchronous payment gateway notification platform event. When a payment, payment authorization, or refund reaches a terminal status through an asynchronous gateway notification, Salesforce Payments publishes one of these events. Subscribe to these events so you can listen and respond to them when they’re published. For example, create a Salesforce Flow that is triggered when a sale or refund settles asynchronously. This object is available in API version 64.0 and later. - **[BatchApexErrorEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-batchapexerrorevent.md)** Notifies subscribers of errors and exceptions that occur during the execution of a batch Apex class. This object is available in API version 44.0 and later. - **[BillingScheduleCreatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-billingschedulecreatedevent.md)** Notifies subscribers when the `/actions/standardCreateBillingScheduleFromOrderItem` request is complete. This object is available in API version 55.0 and later. - **[BillSchdCreatedEventDetail](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-billingschedulecreateddtlevent.md)** Contains information about each order item in the `/actions/standardCreateBillingScheduleFromOrderItem` request and any errors that occurred while processing the request. This object is included in an `BillingScheduleCreatedEvent` message. You can't subscribe to `BillSchdCreatedEventDetail` directly. This object is available in API version 55.0 and later. - **[BulkApi2JobEvent (Beta)](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-bulkapi2jobevent.md)** Notifies subscribers of changes to the status of Bulk API 2.0 query jobs and provides URLs for downloading partial results. This object is available in API version 63.0 and later. - **[CallCoachConfigModifyEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-callcoachconfigmodifyevent.md)** Notifies subscribers of a Conversation Insights configuration change. This object is available in API version 49.0 and later. - **[CartToOrderCompletedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-carttoordercompletedevent.md)** Each row represents information that notifies subscribers when the /actions/standard/createOrderFromCart REST request is complete. If the request is successful, use this event to learn about the Order record. If the request isn’t successful, use this event to learn about the errors associated with the request. This object is available in API version 66.0 and later. - **[CIInsightsEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-ciinsightsevent.md)** For internal use only. - **[CommerceDiagnosticEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-commercediagnosticevent.md)** Tracks checkout, pricing, search, and other activity within your Commerce implementation to monitor events and diagnose issues. This object is available in API version 49.0 and later. - **[ConsentEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-consentevent.md)** Notifies subscribers of changes to consent fields or contact information on all core objects. This object is available in API version 50.0 and later. - **[ConsentUnsubscribeAllEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-consentunsubscribeallevent.md)** Notifies subscribers when a user unsubscribes from all communications on a preference form created in Preference Manager. This object is available in API version 60.0 and later. - **[ConversationInsightEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-conversationinsightevent.md)** Notifies subscribers whenever an Einstein Insight rule is triggered. This object is available in API version 60.0 and later. - **[CreateAssetOrderEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-createassetorderevent.md)** Notifies subscribers that the process started by the `/actions/standard/createOrUpdateAssetFromOrder` or `/actions/standard/createOrUpdateAssetFromOrderItem` request is complete. If the process is successful, use this event to learn about the new assets. If the request isn't successful, use this event to learn about the errors and how to fix them. This object is available in API version 55.0 and later. - **[CreateAssetOrderDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-createassetorderdtlevent.md)** Contains information about an attempt to create or update an asset as a result of `/actions/standard/createOrUpdateAssetFromOrder`. If the request was successful, the event shows information about the asset. If the request failed, the event shows error information. This object is included in an `CreateAssetOrderEvent` message. You can't subscribe to `CreateAssetOrderDtlEvent` directly. This object is available in API version 55.0 and later. - **[CreditInvoiceProcessedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-creditinvoiceprocessedevent.md)** Notifies subscribers when the process started by the `/commerce/invoicing/invoices/{invoiceId}/actions/credit` request is complete. This object is available in API version 55.0 and later. - **[CrMemoProcessErrDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-crmemoprocesserrdtlevent.md)** Contains information about errors that occurred while creating or applying a credit memo as part of a request. This object is included in a `CreditInvoiceProcessedEvent`, `CreditMemoProcessedEvent`, `NegInvcLineProcessedEvent`, or `VoidInvoiceProcessedEvent` message. You can't subscribe to `CrMemoProcessErrDtlEvent` directly. This object is available in API versions 55.0–58.0. In API version 58.0, this field returns a null result. See the `ErrorDetails` field on the `CreditInvoiceProcessedEvent`, `CreditMemoProcessedEvent`, `NegInvcLineProcessedEvent`, or `VoidInvoiceProcessedEvent` object for error information. - **[CreditMemoProcessedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-creditmemoprocessedevent.md)** Notifies subscribers when the process started by the `/commerce/invoicing/credit-memos` request is complete. This object is available in API version 55.0 and later. - **[DataObjectDataChgEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-dataobjectdatachgevent.md)** Notifies subscribers of an action within Data Cloud. This object is available in API version 53.0 and later. - **[DataObjectMetadataChgEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-dataobjectmetadatachgevent.md)** Notifies subscribers of a metadata change within Data Cloud for these objects: Data Lake, Data Model, and Calculated Insight. This object is available in API version 53.0 and later. - **[DatasetExportEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-datasetexportevent.md)** Notifies subscribers on the export of an Analytics dataset. This object is available in API version 41.0 and later. - **[DiscoveryPredictionEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-discoverypredictionevent.md)** Notifies subscribers when Einstein Discovery has written prediction history results. This object is available in API version 57.0 and later. - **[EmailCapturedMatchEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-emailcapturedmatchevent.md)** For internal use only. - **[ExtlRecShrEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-extlrecshrevent.md)** Tracks the record data published from a vendor’s Salesforce org to a connected partner’s org for Partner Connect. This object is available in API version 62.0 and later. - **[ExtlRecShrResultEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-extlrecshrresultevent.md)** Tracks the data and the result of the export or update of the external record share published between a vendor and partner system for Partner Connect. This object is available in API version 62.0 and later. - **[FirstBillPaymentSetupEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-firstbillpaymentsetupevent.md)** Notifies subscribers when a first bill payment is set up. This object is available in API version 60.0 and later. - **[FlowDebugRefreshEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-flowdebugrefreshevent.md)** Notifies subscribers when a flow debug run pauses or completes and its debug output panel in Flow Builder can be refreshed. This object is available in API version 65.0 and later. - **[FlowExecutionErrorEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-flowexecutionerrorevent.md)** Notifies subscribers of errors related to screen flow executions. This object is available in API version 47.0 and later. - **[FlowOrchestrationEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-floworchestrationevent.md)** Notifies subscribers that a paused instance of an orchestration is ready to be resumed. This object is available in API version 53.0 and later. - **[FlowOrchestrationWorkItemEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-floworchestrationworkitemevent.md)** For internal use only. - **[FOStatusChangedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-fostatuschangedevent.md)** Notifies subscribers of changes to the status of a fulfillment order record. Use this event to trigger flows and processes in your order workflow. This object is available in API version 48.0 and later. - **[FulfillOrdItemQtyChgEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-fulfillorditemqtychgevent.md)** Notifies subscribers of changes to the quantity of a fulfillment order line item record. Use this event to trigger flows and processes in your order workflow. This object is available in API version 53.0 and later. - **[InsPlcyEndrStatusEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-insplcyendrstatusevent.md)** Notifies subscribers of the status of the insurance policy endorsement. This object is available in API version 65.0 and later. - **[InsPolicyRnwlQuoteStatusEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-inspolicyrnwlquotestatusevent.md)** Notifies subscribers of the status of a renewal quote during the policy renewal process. This object is available in API version 64.0 and later. - **[InsPolicyRnwlStatusEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-inspolicyrnwlstatusevent.md)** Notifies subscribers of the status of the policy renewal. This object is available in API version 64.0 and later. - **[InteropTopicSubcrEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-interoptopicsubcrevent.md)** Represents the structure of the interoperability topic subscription event that's sent from the publisher to Mulesoft. This object is available in API version 64.0 and later. - **[InvoiceProcessedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-invoiceprocessedevent.md)** Notifies subscribers when the process started by the `/commerce/billing/invoices` request is complete. The process groups billing schedules by grouping keys and creates one invoice per grouping key. `InvoiceProcessedEvent` is a top-level object that contains a list of `InvoiceProcessedDetailEvents`, where each detail event represents an attempt to create one invoice. This object is available in API version 55.0 and later. - **[InvoiceErrorDetailEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-invoiceerrordetailevent.md)** Contains information about errors that occurred during the processing of a `/commerce/billing/invoices` request. This object is included in an `InvoiceProcessedEvent` message. You can't subscribe to `InvoiceErrorDetailEvent` directly. This object is available in API version 55.0 and later. - **[InvoiceProcessedDetailEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-invoiceprocesseddetailevent.md)** Notifies subscribers of the results of an attempt to create an invoice from billing schedules as part of `/commerce/billing/invoices`. InvoiceProcessedDetailEvent contains the results of an attempt to create an invoice from one or more billing schedules that share a grouping key. Each InvoiceProcessedDetailEvent for an action is grouped within the parent object InvoiceProcessedEvent. This object is available in API version 55.0 and later. - **[InvoiceProcPymtExclEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-invoiceprocpymtexclevent.md)** Represents the notification to the subscribers regarding the results of `/commerce/invoicing/invoices/collection/actions/generate` request to generate an invoice from billing schedules without processing payments. This object is available in API version 63.0 and later. - **[ObjectMilestoneCreatedDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-objectmilestonecreateddtlevent.md)** Each row represents information that contains the object milestone created in object milestone created event object. This object is available in API version 68.0 and later. - **[ObjectMilestoneCreatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-objectmilestonecreatedevent.md)** Each row represents information that contains collection of object milestone created details event records for object milestone. Use this event to iterate the list to react per milestone for subscribers. This object is available in API version 68.0 and later. - **[NegInvcLineProcessedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-neginvclineprocessedevent.md)** Notifies subscribers when a negative invoice line is converted to a credit memo. This object is available in API version 56.0 and later. - **[OmniTrackingEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-omnitrackingevent.md)** Notifies subscribers about a user interaction with a FlexCard or OmniScript that's tracked for OmniAnalytics. This object is available in API version 60.0 and later. - **[OrderStatusChangedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-orderstatuschangedevent.md)** Notifies subscribers of changes to the status of an order record. Use this event to trigger flows and processes in your order workflow. This object is available in API version 51.0 and later. - **[OrderSummaryCreatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-ordersummarycreatedevent.md)** Notifies subscribers of the creation of an order summary record. Use this event to trigger flows and processes in your order workflow. This object is available in API version 48.0 and later. - **[OrderSumStatusChangedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-ordersumstatuschangedevent.md)** Notifies subscribers of changes to the status of an order summary record. Use this event to trigger subscribers such as flows in your order workflow. This object is available in API version 48.0 and later. - **[PaymentCreationEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-paymentcreationevent.md)** Notifies subscribers when the process started by the `/actions/standard/paymentSale` request is complete. This object is available in API version 55.0 and later. - **[PendingOrdSumProcEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-pendingordsumprocevent.md)** Notifies subscribers that a PendingOrderSummary record was processed. If the process succeeded, an OrderSummary was created and the PendingOrderSummary can be deleted. Use this event to trigger subscribers such as flows in your order workflow. This object is available in API version 56.0 and later. - **[PlaceOrderCompletedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-placeordercompletedevent.md)** Notifies subscribers of an order being created or updated by invoking the Place Order API or the Place Sales Transaction API. This object is available in API version 63.0 and later. - **[PlatformStatusAlertEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-platformstatusalertevent.md)** Notifies subscribers of alerts that occur during the processing of a user request or service job execution. This object is available in API version 45.0 and later. - **[ProcessExceptionEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-processexceptionevent.md)** Notifies subscribers of errors that occur during payment processing (capture, apply, and refund) on an order summary. Use this event to trigger subscribers such as flows in your order workflow. This object is available in API version 50.0 and later. - **[QuoteSaveEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-quotesaveevent.md)** Notifies subscribers that the process started by the `/actions/standard/quotesaveevent` request is complete. If the process is successful, use this event to learn about the updated quote. If the request isn't successful, use this event to learn about the errors and how to fix them. This object is available in API version 58.0 and later. - **[QuoteToOrderCompletedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-quotetoordercompletedevent.md)** Notifies subscribers when the `/actions/standard/createOrderFromQuote` REST request is complete. If the request is successful, use this event to learn about the Order record. If the request isn’t successful, use this event to learn about the errors associated with the request. This object is available in API version 56.0 and later. - **[QuoteToOrderErrDtlEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-quotetoordererrdtlevent.md)** Contains information about any errors that occurred while processing the `/actions/standard/createOrderFromQuote` REST request. One `QuoteToOrderErrDtlEvent` record is created for each error that occurred. This object is included in an `QuoteToOrderCompletedEvent` message. You can't subscribe to `QuoteToOrderErrDtlEvent` directly. This object is available in API version 56.0 and later. - **[RealtimeAlertEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-realtimealertevent.md)** Notifies subscribers of Amazon CloudWatch alarm events from your Service Cloud Voice Amazon Connect instance. This object is available in API version 54.0 and later. - **[RemoteKeyCalloutEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-remotekeycalloutevent.md)** Notifies subscribers of callouts that fetch encrypted key material from a customer endpoint. This object is available in API versions 45.0 and later. - **[SalesMeetingBookedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-salesmeetingbookedevent.md)** Notifies subscribers when a lead books a sales meeting via an inbound web agent or other service. This object is available in API version 65.0 and later. - **[SrcPredJobStatusChgEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-srcpredjobstatuschgevent.md)** Notifies subscribers that the Data Cloud prediction job’s status is changed. This object is available in API version 50.0 and later. - **[SearchIndexJobStatusEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-searchindexjobstatusevent.md)** Notifies subscribers of changes to the status of the Data Cloud search index job, such as index refresh status and index run-time status. This object is available in API version 60.0 and later. - **[ServiceAppointmentEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-serviceappointmentevent.md)** Notifies subscribers of the service appointment details that are generated from the event platform. This object is available in API version 59.0 and later. - **[VideoCallEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-videocallevent.md)** For internal use only. - **[VideoCallPurgeEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-videocallpurgeevent.md)** For internal use only. - **[VideoCallRevisedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-videocallrevisedevent.md)** For internal use only. - **[VoidInvoiceProcessedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-voidinvoiceprocessedevent.md)** Notifies subscribers when the process started by the `/commerce/invoicing/invoices/{invoiceId}/actions/void` request is complete. The request attempts to void an invoice by crediting an invoice and changing its status to Voided, which prevents further changes. This object is available in API version 55.0 and later. This object is available in API version 55.0 and later. - **[WebCartAbandonedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-webcartabandonedevent.md)** Notifies subscribers of an abandoned cart. This object is available in API version 63.0 and later. - **[WebStoreUserCreatedEvent](https://developer.salesforce.com/docs/platform/platform-events/guide/sforce-api-objects-webstoreusercreatedevent.md)** Notifies subscribers of the creation of a new user for a WebStore. This object is available in API version 59.0 and later. - **[Real-Time Event Monitoring Objects](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-objects-monitoring.md)** Check out the standard platform event and object pairs for Real-Time Event Monitoring. For most platform events used in Real-Time Event Monitoring, corresponding objects store the event data. For more information, see [Real-Time Event Monitoring](https://help.salesforce.com/s/articleView?id=xcloud.real_time_event_monitoring_overview.htm&type=5) in Salesforce Help. # Standard Platform Event Objects Check out the standard platform events that Salesforce publishes. - **[Change Data Capture Events](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-objects-change-data-capture.md)** Salesforce Change Data Capture publishes change events, which represent changes to Salesforce records. Changes include record creation, updates to an existing record, deletion of a record, and undeletion of a record. Change Data Capture events are available since API version 44.0. - **[Standard Platform Event Object List](https://developer.salesforce.com/docs/platform/platform-events/guide/platform-events-objects-list.md)** Salesforce publishes standard platform events in response to an action that occurred in the org or to report errors. For example, LoginEventStream monitors user login activity and BatchApexErrorEvent reports errors encountered in batch Apex jobs. You can subscribe to a standard platform event using the subscription mechanism that the event supports. # Standard Visualforce Component Reference This section provides a full list of standard Visualforce components. - **[analytics:reportChart](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-analytics-reportchart.md)** - **[apex:actionFunction](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-actionfunction.md)** A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. - **[apex:actionPoller](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-actionpoller.md)** - **[apex:actionRegion](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-actionregion.md)** An area of a Visualforce page that demarcates which components should be processed by the Force.com server when an AJAX request is generated. - **[apex:actionStatus](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-actionstatus.md)** - **[apex:actionSupport](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-actionsupport.md)** A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs, such as a button click or hover. - **[apex:areaSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-areaseries.md)** - **[apex:attribute](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-attribute.md)** - **[apex:axis](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-axis.md)** - **[apex:barSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-barseries.md)** - **[apex:canvasApp](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-canvasapp.md)** - **[apex:chart](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chart.md)** - **[apex:chartLabel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chartlabel.md)** - **[apex:chartTips](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-charttips.md)** - **[apex:column](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-column.md)** - **[apex:commandButton](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-commandbutton.md)** A button that is rendered as an HTML input element with the type attribute set to submit, reset, or image, depending on the `` tag's specified values. - **[apex:commandLink](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-commandlink.md)** A link that executes an action defined by a controller, and then either refreshes the current page, or navigates to a different page based on the PageReference variable that is returned by the action. - **[apex:component](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-component.md)** - **[apex:componentBody](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-componentbody.md)** - **[apex:composition](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-composition.md)** - **[apex:dataList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-datalist.md)** - **[apex:dataTable](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-datatable.md)** - **[apex:define](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-define.md)** - **[apex:detail](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-detail.md)** - **[apex:dynamicComponent](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-dynamiccomponent.md)** - **[apex:emailPublisher](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-emailpublisher.md)** - **[apex:enhancedList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-enhancedlist.md)** - **[apex:facet](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-facet.md)** - **[apex:flash](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-flash.md)** - **[apex:form](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-form.md)** - **[apex:gaugeSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-gaugeseries.md)** - **[apex:iframe](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-iframe.md)** A component that creates an inline frame within a Visualforce page. With a frame, you can keep some information visible while other information is scrolled or replaced. - **[apex:image](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-image.md)** - **[apex\:include](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-include.md)** - **[apex\:includeLightning](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-includelightning.md)** - **[apex\:includeScript](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-includescript.md)** - **[apex:inlineEditSupport](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inlineeditsupport.md)** - **[apex:input](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-input.md)** - **[apex:inputCheckbox](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputcheckbox.md)** An HTML input element of type checkbox. Use this component to get user input for a controller method that does not correspond to a field on a Salesforce object. - **[apex:inputField](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputfield.md)** - **[apex:inputFile](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputfile.md)** - **[apex:inputHidden](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputhidden.md)** An HTML input element of type hidden, that is, an input element that is invisible to the user. Use this component to pass variables from page to page. - **[apex:inputSecret](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputsecret.md)** An HTML input element of type password. Use this component to get user input for a controller method that does not correspond to a field on a Salesforce object, for a value that is masked as the user types. - **[apex:inputText](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputtext.md)** - **[apex:inputTextarea](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-inputtextarea.md)** - **[apex:insert](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-insert.md)** - **[apex:legend](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-legend.md)** - **[apex:lineSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-lineseries.md)** - **[apex:listViews](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-listviews.md)** - **[apex:logCallPublisher](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-logcallpublisher.md)** - **[apex:map](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-map.md)** - **[apex:mapInfoWindow](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-mapinfowindow.md)** - **[apex:mapMarker](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-mapmarker.md)** - **[apex:message](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-message.md)** - **[apex:messages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messages.md)** - **[apex:milestoneTracker](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-milestonetracker.md)** - **[apex:outputField](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-outputfield.md)** - **[apex:outputLabel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-outputlabel.md)** - **[apex:outputLink](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-outputlink.md)** - **[apex:outputPanel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-outputpanel.md)** - **[apex:outputText](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-outputtext.md)** - **[apex:page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-page.md)** A single Visualforce page. All pages must be wrapped inside a single `` component tag. - **[apex:pageBlock](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pageblock.md)** - **[apex:pageBlockButtons](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pageblockbuttons.md)** - **[apex:pageBlockSection](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pageblocksection.md)** - **[apex:pageBlockSectionItem](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pageblocksectionitem.md)** - **[apex:pageBlockTable](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pageblocktable.md)** - **[apex:pageMessage](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pagemessage.md)** - **[apex:pageMessages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pagemessages.md)** - **[apex:panelBar](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-panelbar.md)** - **[apex:panelBarItem](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-panelbaritem.md)** - **[apex:panelGrid](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-panelgrid.md)** - **[apex:panelGroup](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-panelgroup.md)** - **[apex:param](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-param.md)** - **[apex:pieSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-pieseries.md)** - **[apex:radarSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-radarseries.md)** - **[apex:relatedList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-relatedlist.md)** - **[apex:remoteObjectField](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-remoteobjectfield.md)** - **[apex:remoteObjectModel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-remoteobjectmodel.md)** - **[apex:remoteObjects](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-remoteobjects.md)** - **[apex:repeat](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-repeat.md)** - **[apex:scatterSeries](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-scatterseries.md)** - **[apex:scontrol](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-scontrol.md)** - **[apex:sectionHeader](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-sectionheader.md)** - **[apex:selectCheckboxes](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-selectcheckboxes.md)** A set of related checkbox input elements displayed in a table. - **[apex:selectList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-selectlist.md)** - **[apex:selectOption](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-selectoption.md)** - **[apex:selectOptions](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-selectoptions.md)** - **[apex:selectRadio](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-selectradio.md)** A set of related radio button input elements, displayed in a table. Unlike checkboxes, only one radio button can be selected at a time. - **[apex:slds](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-slds.md)** - **[apex:stylesheet](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-stylesheet.md)** - **[apex:tab](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-tab.md)** A single tab in an ``. - **[apex:tabPanel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-tabpanel.md)** A page area that displays as a set of tabs. When a user clicks a tab header, the tab's associated content displays, hiding the content of other tabs. - **[apex:toolbar](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-toolbar.md)** - **[apex:toolbarGroup](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-toolbargroup.md)** - **[apex:variable](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-variable.md)** - **[apex:vote](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-vote.md)** - **[chatter:feed](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-feed.md)** Displays the Chatter feed for a record or a user. - **[chatter:feedWithFollowers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-feedwithfollowers.md)** - **[chatter:follow](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-follow.md)** - **[chatter:followers](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-followers.md)** - **[chatter:newsfeed](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-newsfeed.md)** - **[chatter:userPhotoUpload](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatter-userphotoupload.md)** - **[chatteranswers:aboutme](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-aboutme.md)** - **[chatteranswers:allfeeds](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-allfeeds.md)** - **[chatteranswers:changepassword](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-changepassword.md)** - **[chatteranswers:datacategoryfilter](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-datacategoryfilter.md)** - **[chatteranswers:feedfilter](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-feedfilter.md)** - **[chatteranswers:feeds](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-feeds.md)** - **[chatteranswers:forgotpassword](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-forgotpassword.md)** - **[chatteranswers:forgotpasswordconfirm](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-forgotpasswordconfirm.md)** - **[chatteranswers:guestsignin](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-guestsignin.md)** - **[chatteranswers:help](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-help.md)** - **[chatteranswers:login](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-login.md)** - **[chatteranswers:registration](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-registration.md)** - **[chatteranswers:searchask](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-searchask.md)** - **[chatteranswers:singleitemfeed](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-chatteranswers-singleitemfeed.md)** - **[flow:interview](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-flow-interview.md)** - **[ideas:detailOutputLink](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-ideas-detailoutputlink.md)** - **[ideas:listOutputLink](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-ideas-listoutputlink.md)** - **[ideas:profileListOutputLink](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-ideas-profilelistoutputlink.md)** - **[knowledge:articleCaseToolbar](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-knowledge-articlecasetoolbar.md)** - **[knowledge:articleList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-knowledge-articlelist.md)** - **[knowledge:articleRendererToolbar](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-knowledge-articlerenderertoolbar.md)** - **[knowledge:articleTypeList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-knowledge-articletypelist.md)** - **[knowledge:categoryList](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-knowledge-categorylist.md)** - **[liveAgent:clientChat](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchat.md)** - **[liveAgent:clientChatAlertMessage](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatalertmessage.md)** - **[liveAgent:clientChatCancelButton](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatcancelbutton.md)** - **[liveAgent:clientChatEndButton](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatendbutton.md)** - **[liveAgent:clientChatFileTransfer](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatfiletransfer.md)** - **[liveAgent:clientChatInput](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatinput.md)** - **[liveAgent:clientChatLog](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatlog.md)** - **[liveAgent:clientChatLogAlertMessage](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatlogalertmessage.md)** - **[liveAgent:clientChatMessages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatmessages.md)** - **[liveAgent:clientChatQueuePosition](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatqueueposition.md)** - **[liveAgent:clientChatSaveButton](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatsavebutton.md)** - **[liveAgent:clientChatSendButton](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatsendbutton.md)** - **[liveAgent:clientChatStatusMessage](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-liveagent-clientchatstatusmessage.md)** - **[messaging:attachment](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messaging-attachment.md)** Compose an attachment and append it to the email. - **[messaging:emailHeader](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messaging-emailheader.md)** - **[messaging:emailTemplate](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messaging-emailtemplate.md)** - **[messaging:htmlEmailBody](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messaging-htmlemailbody.md)** - **[messaging:plainTextEmailBody](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-messaging-plaintextemailbody.md)** - **[site:googleAnalyticsTracking](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-site-googleanalyticstracking.md)** - **[site:previewAsAdmin](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-site-previewasadmin.md)** - **[social:profileViewer](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-social-profileviewer.md)** - **[support:caseArticles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-support-casearticles.md)** - **[support:caseFeed](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-support-casefeed.md)** - **[support:caseUnifiedFiles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-support-caseunifiedfiles.md)** - **[support:clickToDial](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-support-clicktodial.md)** - **[support:portalPublisher](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-support-portalpublisher.md)** - **[topics:widget](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-topics-widget.md)** - **[wave:dashboard](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-compref-wave-dashboard.md)** # Standard Visualforce Components and Base Lightning Web Components Side by Side Use this table to find the equivalent base Lightning web component for a specific standard Visualforce component. | Visualforce component | Lightning web component | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `apex:pageBlock` | `lightning-card` | | `apex:pageBlockButtons` | Set actions slot on `lightning-card` | | `apex:pageBlockSection` | `lightning-accordion` and `lightning-accordion-section` | | `apex:pageBlockSectionItem` | `lightning-layout` and `lightning-layout-item` | | `apex:toolbarGroup` | `lightning-layout` and `lightning-layout-item` | | `apex:panelGrid` | `lightning-layout` and `lightning-layout-item` | | `apex:panelGroup` | `lightning-layout` and `lightning-layout-item` | | `apex:tabPanel` | `lightning-tabset` | | `apex:tab` | `lightning-tab` | | `apex:repeat` | `template for:each or iterator` | | `apex:pageBlockTable` | `lightning-datatable` | | `apex:dataTable` | `lightning-datatable` | | `apex:inlineEditSupport` | `lightning-datatable` with inline editing in editable columns | | `apex:image` | `lightning-platform-resource-loader` | | `apex:stylesheet` | `lightning-platform-resource-loader` | | `apex:includeScript` | `lightning-platform-resource-loader` | | `apex:map` | `lightning-map` | | `apex:form` | `lightning-record-form`, `lightning-record-view-form`, and `lightning-record-edit-form` | | `apex:input` | `lightning-input` and `lightning-slider` | | `apex:inputCheckbox` | `lightning-input` type="checkbox" or `lightning-input` type="checkbox-button" | | `apex:inputFile` | `lightning-input` type="file" or `lightning-file-upload` | | `apex:inputHidden` | `lightning-input` class="slds-hide" | | `apex:inputSecret` | `lightning-input` type="password" | | `apex:inputText` | `lightning-input` type="text" | | `apex:inputTextArea` | `lightning-textarea` | | `apex:inputField` | `lightning-input-field` | | `apex:selectCheckboxes` | `lightning-checkbox-group` | | `apex:selectList` | `lightning-combobox` or `lightning-dual-listbox` | | `apex:selectRadio` | `lightning-radio-group` | | `apex:outputLabel` | Set label attribute on `lightning-input` | | `apex:outputField` | `lightning-output-field` | | `apex:outputLink` | `lightning-formatted-url` | | `apex:outputText` | `lightning-formatted-datetime`, `lightning-formatted-number`, `lightning-formatted-rich-text`, `lightning-formatted-text`, or `lightning-formatted-time` | | `apex:commandButton` | `lightning-button`, `lightning-button-stateful`, `lightning-button-icon`, or `lightning-button-icon-stateful` | | `apex:commandLink` | `lightning-button` with bare variant | | `apex:pageMessage` | `lightning-platform-show-toast-event` | | `apex:messages` or `apex:message` | Custom validity on `lightning-input` | | `apex:pageMessages` | Automatic for `lightning-record-form`. Use `lightning-messages` in `lightning-record-view-form` or `lightning-record-edit-form` | **See Also** - [_Salesforce Developers Blog:_ New Resources for Moving from Visualforce to Lightning Web Components](https://developer.salesforce.com/blogs/2020/07/new-resources-for-moving-from-visualforce-to-lightning-web-components.html) - [_Lightning Component Reference_: Components](https://developer.salesforce.com/docs/platform/lightning-component-reference/guide/components.html) # Standard Visualforce Pages Normal Visualforce pages render well on mobile browsers, and can be used as-is, with a modest reduction of the user experience compared to mobile-optimized Web pages. Pages display as they would on the full Salesforce site, and won’t visually match other Salesforce app features. ## Limitations Limitations to the user experience include: - Tap targets—buttons, links, form fields, and so on—are optimized for mouse cursors, and can be difficult to hit accurately with a fingertip. - The visual design is unchanged, and may not fit with the mobile-optimized, modern visual design of the Salesforce mobile app. If your development timeline is aggressive, you might find these limitations acceptable. ## Example of a Standard Visualforce Page The following code provides a sample for a standard Visualforce page that allows a user to edit a warehouse record. The edit feature is provided by the standard controller for the object. ```markup ``` This page can be used in both the Salesforce mobile app and the full Salesforce site. It displays as a standard desktop Visualforce page in both contexts. # Standard-Volume Platform Event Allocations These allocations are for standard-volume events defined in API version 44.0 and earlier. **important:** You can no longer define new standard-volume custom platform events. New platform events are high volume by default. Standard-volume custom platform events will be retired in Summer ’27. To migrate existing standard-volume events, see [Migrate Standard-Volume Platform Events to High-Volume Platform Events Before Retirement](https://help.salesforce.com/s/articleView?id=002280033&type=1). |Description|Performance and Unlimited Editions|Enterprise Edition|Developer Edition and Professional Edition (with API Add-On)| |-----------|----------------------------------|------------------|------------------------------------------------------------| |Event Delivery: maximum number of delivered event messages in the last 24 hours, shared by all CometD clients:sup[1]|50,000|25,000|10,000| |Event Publishing: maximum number of event messages published per hour|100,000|100,000|1,000| If you exceed the event delivery allocation, you receive this error: `403::Organization total events daily limit exceeded`. The error is returned in the Bayeux `/meta/connect` channel when a CometD subscriber first connects or in an existing subscriber connection. For more information, see [Streaming API Error Codes](https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/streaming_error_codes.htm) in the [Streaming API Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/intro_stream.htm). Standard-volume event messages that are generated after exceeding the allocation are stored in the event bus. You can retrieve stored standard-volume event messages as long as they’re within the 24-hour retention window. To monitor your standard-volume event delivery usage, use the `limits` REST API resource, and inspect the `DailyStandardVolumePlatformEvents` value. And to monitor the publishing usage, inspect the `HourlyPublishedStandardVolumePlatformEvents` value. For more information, see [List Organization Limits](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_limits.htm) in the *REST API Developer Guide*. :sup[1]To request a higher number of standard-volume events delivered to CometD clients, contact Salesforce to purchase an add-on license. The add-on license increases your daily limit of delivered events by 100,000 more events. For example, for Unlimited Edition, the add-on license increases the daily limit of delivered events from 50,000 to 150,000 events. You can purchase multiple add-ons to meet your event requirements for CometD clients. To avoid deployment problems and degradation in service, we recommend that the number of events delivered to CometD clients not exceed 5 million per day. If you require more external events, contact your Salesforce representative to understand how the product can scale to meet your needs. # startOf() Returns a date that is the start of a unit of time for the given date. ## Signature `startOf(string | number | Date date, string unit)` ## Parameters **_date_:** Type: `string | number | Date`. A datetime string in ISO8601 format, or a timestamp in milliseconds, or a `Date` object. **_unit_:** Type: `string`. A datetime unit. Options are 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'. ## Returns **Type: `Date`** A JavaScript `Date` object. If a unit is not provided, returns a parsed date. ## Sample Code ```javascript var date = "2015-10-9"; // Returns "Thu Oct 01 2015 00:00:00 GMT-0700 (PDT)" $A.localizationService.startOf(date, 'month'); ``` # Static Analyzer Validation Rules The static analyzer validates that various code constructs and references in Lightning web components, such as wire decorators and server calls, support offline priming. The majority of the rules focus on determining whether all code dependencies, such as imports and modules, can be resolved; or on correct usage of offline-compatible wire adapters. Using a wire provides an efficient and mostly transparent mechanism to deliver required data for a given set of Lightning web components. Today, not all wire adapters are enabled for offline use, and even those that are must be used correctly to work while offline. Without a properly formatted wire, the number of network requests increases, components render slowly, and performance suffers. For offline support, mobile apps at Salesforce use these wires to ensure the correct data for each record and its components are always ready to use. A wire that doesn’t align with the validation rules defined in this package can result in features implemented with Lightning web components not working correctly when offline. For more information on wires and how to use them, see [Use the Wire Service to Get Data](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.data_wire_service) in the _Lightning Web Components Developer Guide_. # Status Codes and Error Responses Either when an error occurs or when a response is successful, the response header contains an HTTP code, and the response body usually contains: - The HTTP response code - The message accompanying the HTTP response code - The field or object where the error occurred (if the response returns information about an error) |HTTP response code|Description| |------------------|-----------| |200|“OK” success code, for GET, HEAD, and some PATCH requests.| |201|“Created” success code, for POST requests and some PATCH requests.| |204|“No Content” success code, for DELETE requests and some PATCH requests.| |300|The value returned when an external ID exists in more than one record. The response body contains the list of matching records.| |304|The request content hasn’t changed since a specified date and time. The date and time is provided in a `If-Modified-Since` header. See [Get Object Metatdata Changes](https://developer.salesforce.com/docs/platform/api-rest/do-me/sobject-describe-with-ifmodified-header.md) for an example.| |400|The request couldn’t be understood, usually because the JSON or XML body contains an error.| |401|The session ID or OAuth token used has expired or is invalid. The response body contains the `message` and `errorCode`.| |403|The request has been refused. Verify that the logged-in user has appropriate permissions. If the error code is REQUEST_LIMIT_EXCEEDED, you’ve exceeded API request limits in your org.| |404|The requested resource couldn’t be found. Check the URI for errors, and verify that there are no sharing issues.| |405|The method specified in the Request-Line isn’t allowed for the resource specified in the URI.| |409|The request couldn’t be completed due to a conflict with the current state of the resource. Check that the API version is compatible with the resource you’re requesting.| |410|The requested resource has been retired or removed. Delete or update any references to the resource.| |412|The request wasn’t executed because one or more of the preconditions that the client specified in the request headers wasn’t satisfied. For example, the request includes an [`If-Unmodified-Since`](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-rest-conditional-requests.md) header, but the data was modified after the specified date.| |414|The length of the URI exceeds the 16,384-byte limit.| |415|The entity in the request is in a format that’s not supported by the specified method.| |420|Salesforce Edge doesn’t have routing information available for this request host. Contact Salesforce Customer Support.| |428|The request wasn’t executed because it wasn’t conditional. Add one of the [Conditional Request Headers](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-rest-conditional-requests.md), such as `If-Match`, to the request and resubmit it.| |431|The combined length of the URI and headers exceeds the 16,384-byte limit.| |500|An error has occurred within Lightning Platform, so the request couldn’t be completed. Contact Salesforce Customer Support.| |502|Salesforce Edge wasn’t able to communicate successfully with the Salesforce instance.| |503|The server is unavailable to handle the request. Typically this issue occurs if the server is down for maintenance or is overloaded.| ## Incorrect ID example Using a non-existent ID in a request using JSON or XML (request_body.json or request_body.xml) ```nolang [ { "fields" : [ "Id" ], "message" : "Account ID: id value of incorrect type: 001900K0001pPuOAAU", "errorCode" : "MALFORMED_ID" } ] ``` ## Resource doesn’t exist Requesting a resource that doesn’t exist, for example, you try to create a record using a misspelled object name ```nolang [ { "message" : "The requested resource does not exist", "errorCode" : "NOT_FOUND" } ] ``` For extended error codes, see [Core Data Types Used in API Calls](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_concepts_core_data_objects.htm). # Step 1: Create an Object Create an Invoice Statement object from the user interface. After you create a PushTopic and subscribe to it, you’ll get notifications when an Invoice Statement record is created, updated, deleted, or undeleted. You’ll create the object with the user interface. 1. From your management settings for custom objects, if you’re using Salesforce Classic, click **New Custom Object**, or if you’re using Lightning Experience, select **Create** | **Custom Object**. 2. Define the custom object. - In the **Label field**, type `Invoice Statement`. - In the **Plural Label** field, type `Invoice Statements`. - Select **Starts with vowel sound**. - In the **Record Name** field , type `Invoice Number`. - In the **Data Type** field , select `Auto Number`. - In the **Display Format** field, type `INV-{0000}`. - In the **Starting Number** field, type `1`. 3. Click **Save**. 4. Add a Status field. 1. Scroll down to the Custom Fields & Relationships related list and click **New**. 2. For Data Type, select `Picklist` and click **Next**. 3. In the Field Label field, type `Status`. 4. Type the following picklist values in the box provided, with each entry on its own line. ```nolang Open Closed Negotiating Pending ``` 5. Select the checkbox for **Use first value as default value**. 6. Click **Next**. 7. For field-level security, select `Read Only` and then click **Next**. 8. Click **Save & New** to save this field and create a new one. 5. Now create an optional Description field. 1. In the Data Type field, select `Text Area` and click **Next**. 2. In the Field Label and Field Name fields, enter `Description`. 3. Click **Next**, accept the defaults, and click **Next** again. 4. Click **Save** to go the detail page for the Invoice Statement object. Your Invoice Statement object should now have two custom fields. # Step 1: Create an Object Create an Invoice Statement object from the user interface. 1. In Setup, from your management settings for custom objects, if you’re using Salesforce Classic, click **New Custom Object**, or if you’re using Lightning Experience, select **Create** | **Custom Object**. 2. Define the custom object. - In the Label field, enter `Invoice Statement`. - In the Plural Label field, enter `Invoice Statements`. - Select **Starts with vowel sound**. - In the Record Name field, enter `Invoice Number`. - In the Data Type field, select **Auto Number**. - In the Display Format field, enter `INV-{0000}`. - In the Starting Number field, enter `1`. 3. Save your work. 4. Add a Status field. 1. In Custom Fields & Relationships, click **New**. 2. For Data Type, select `Picklist`, and then click **Next**. 3. In the Field Label field, enter `Status`. 4. For Values, select **Enter values, with each value separated by a new line**. 5. Enter these picklist values with each entry on its own line. ```nolang Open Closed Negotiating Pending ``` 6. Click **Use first value as default value**. 7. Click **Next**. 8. For field-level security, select `Read Only`, and then click **Next**. 9. Click **Save & New** to save this field and create another. 5. Now create an optional Description field. 1. In the Data Type field, select `Text Area`, and then click **Next**. 2. In the Field Label and Field Name fields, enter `Description`. 3. Click **Next**, accept the defaults, and then click **Next** again. 4. Click **Save** to go the detail page for the Invoice Statement object. Your Invoice Statement object now shows two custom fields. # Step 1: Set Up a Salesforce Developer Edition Org This Quick Start suggests using a Developer Edition org. Sign up for a Salesforce Developer Edition org before trying Bulk API 2.0 with this Quick Start. If you’re not already a member of the developer community, go to [developer.salesforce.com/signup](https://developer.salesforce.com/signup), and follow the instructions for signing up for a Developer Edition account. You can also use a scratch org or sandbox to follow along with these examples. **note:** Developer Edition orgs have a data storage maximum of 5 MB. This limit doesn’t prevent you from working with these examples. # Step 1: Sign up for Salesforce Developer Edition Use Salesforce Developer Edition to develop, stage, and test your API code against sample data. Using a separate org to develop your applications protects your live data during testing. This recommendation is especially true for applications that insert, update, or delete data (as opposed to simply reading data). After you’ve tested your code, you can implement it in an edition with API access. To create a Developer Edition org, go to [developer.salesforce.com/signup](https://developer.salesforce.com/signup) and follow the instructions for signing up for a Developer Edition organization. If you already have a Developer Edition organization, verify that your user profile has the API Enabled permission. This permission is enabled by default, but may have been changed by an administrator. For more information, see Salesforce Help. **See Also** - [*Salesforce Help*: User Permissions](https://help.salesforce.com/s/articleView?id=platform.admin_userperms.htm&type=5) - [*Knowledge Article*: Salesforce editions with API access](https://help.salesforce.com/articleView?id=000326486&type=1&mode=1) # Step 1. Developer Registration with Mobile OS Vendors This step asks the OS vendor to be prepared to handle Salesforce push notifications sent to your app. Developer registration also provides some information you’ll need to finish configuring your Salesforce external client app. To register your mobile client app, follow the process for your target mobile OS. ## Android Registration When developing an Android app that supports push notifications, remember these key points: - You must be a member of the Android Developer Program. - You can test FCM push services only on an Android device with either the Android Market app or Google Play Services installed. Push notifications don’t work on an Android emulator. Salesforce sends push notifications to Android apps through the Firebase Cloud Messaging for Android (FCM) framework. See [https://firebase.google.com/docs/cloud-messaging](https://firebase.google.com/docs/cloud-messaging) for an overview of this framework. To begin, create a Google API project for your app. Your project must have the FCM for Android feature enabled. See [https://firebase.google.com/docs/cloud-messaging/android/client](https://firebase.google.com/docs/cloud-messaging/android/client) for instructions on setting up your project. The setup process for your Google API project creates a key for your app. Once you’ve finished the project configuration, you’ll need to add the Key for Server Applications (API Key) from FCM to your external client app settings. Push notification registration occurs at the end of the OAuth login flow. Therefore, an app does not receive push notifications unless and until the user logs into a Salesforce org. ## iOS Registration When developing an iOS app that supports push notifications, remember these key points: - You must be a member of the iOS Developer Program. - You can test Apple push services only on an iOS physical device. Push notifications don’t work in the iOS simulator. - There are no guarantees that all push notifications will reach the target device, even if the notification is accepted by Apple. - Apple Push Notification Services setup requires the use of the OpenSSL command line utility provided in Mac OS X. Before you can complete registration on the Salesforce side, you need to register with Apple Push Notification Services (APNS). Registration with APNS requires the following items. **Certificate Signing Request (CSR) File** Generate this request using the Keychain Access feature in Mac OS X. You’ll also use OpenSSL to export the CSR private key to a file for later use. **App ID from iOS Developer Program** In the iOS Developer Member Center, create an ID for your app, then use the CSR file to generate a certificate. Next, use OpenSSL to combine this certificate with the private key file to create an appkey.p12 file. You’ll need this file later to configure your external client app. **iOS Provisioning Profile** From the iOS Developer Member Center, create a new provisioning profile using your iOS app ID and developer certificate. You then select the devices to include in the profile and download to create the provisioning profile. You can then add the profile to Xcode. Install the profile on your test device using Xcode's Organizer. When you’ve completed the configuration, sign and build your app in Xcode. Check the build logs to verify that the app is using the correct provisioning profile. To view the content of your provisioning profile, run the following command at the Terminal window: `security cms -D -i <`_your profile_`>.mobileprovision` For detailed instructions see: - [Local and Push Notification Programming Guide at https://developer.apple.com/library/mac](https://developer.apple.com/library/mac) - [http://www.raywenderlich.com/32960/](http://www.raywenderlich.com/32960/) # Step 2: Authentication The first action in an API-based integration is authenticating requests with your Salesforce org. Bulk API 2.0 and Bulk API use different authentication methods. Bulk API 2.0 is a REST-based API that supports all OAuth 2.0 flows supported by other Salesforce REST APIs. Bulk API 2.0 requires an access token (also known as a “bearer token”) for authentication. This topic, and the remainder of this Quick Start, describe getting an access token and using it to make Bulk API 2.0 requests with cURL. In contrast, Bulk API uses a session ID obtained with an X-SFDC-Session header fetched with SOAP API’s `login()` call. For an example, see [Step 1: Log In Using the SOAP API](https://developer.salesforce.com/docs/platform/api-asynch/quickstart/asynch-api-quickstart-login.md). **note:** These examples use an access token. Any API call that requires a session ID doesn’t work with these instructions. While it’s possible to create and authenticate against your own [connected app](https://help.salesforce.com/s/articleView?id=xcloud.connected_app_create.htm&type=5), Salesforce CLI is used in these Quick Start examples for convenience. Effectively, Salesforce CLI is a connected app with which you can authenticate and requires no work to configure. The examples in this Quick Start use the cURL tool to send HTTP requests that access, create, and manipulate resources in Salesforce. If you use a different tool to send requests, you can use the same elements from the cURL examples to send requests. Although these instructions describe a scenario with a Developer org, they work in the same way with any type of Salesforce org. The cURL tool is pre-installed on many Linux and macOS systems. Windows users can download a version at [curl.se](https://curl.se/). When using HTTPS on Windows, ensure that your system meets the cURL requirements for SSL. **note:** cURL is an open-source tool and isn’t supported by Salesforce. ## Get an Access Token with Salesforce CLI Use the access token (also known as a “bearer token”) that you get from Salesforce CLI to authenticate cURL requests. 1. Install or update Salesforce CLI. 1. If you already have Salesforce CLI installed, update it using the instructions in [Update Salesforce CLI](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_update_cli.htm). 2. If you need to [Install Salesforce CLI](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm), install the latest version for your operating system. 3. [Verify Your Installation](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm#sfdx_setup_install_cli_verify). 2. Log in to your Developer org with Salesforce CLI. ```nolang sf org login web ``` A browser opens to https://login.salesforce.com. To log in to a sandbox, append the `--instance-url` flag and specify your sandbox URL: ```nolang sf org login web --instance-url https://MyDomainName--SandboxName.sandbox.my.salesforce.com ``` 3. In the browser, log in to your Developer org or sandbox with your user’s credentials. 4. In the browser, click **Allow** to allow access. At the command line, you see a similar confirmation message. ```nolang Successfully authorized juliet.capulet@empathetic-wolf-g5qddtr.com with org ID 00D5fORGIDEXAMPLE ``` 5. At the command line, get the access token by viewing authentication information about your org. ```nolang sf org display --target-org ``` For example: ```nolang sf org display --target-org juliet.capulet@empathetic-wolf-g5qddtr.com ``` Example command output: ```nolang === Org Description KEY VALUE ─────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────── Access Token 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE Api Version 59.0 Client Id PlatformCLI Created By jules@sf.com Created Date 2023-11-16T20:35:21.000+0000 Dev Hub Id jules@sf.com Edition Developer Expiration Date 2023-11-23 Id 00D5fORGIDEXAMPLE Instance Url https://MyDomainName.my.salesforce.com Org Name Dreamhouse Signup Username juliet.capulet@empathetic-wolf-g5qddtr.com Status Active Username juliet.capulet@empathetic-wolf-g5qddtr.com ``` In the command output, make note of the long Access Token string and the Instance Url string. You need both to make cURL requests. **note:** To get a new token after your access token expires, repeat this step of viewing your authentication information. ## Optional Salesforce CLI Shortcuts After you’ve authenticated successfully, try out these optional shortcuts in your cURL workflow to streamline future authentication with the Salesforce CLI. **List My Orgs** ```nolang sf org list ``` Lists all the orgs that you’ve created or authenticated to. **Open My Org** ```nolang sf org open --target-org ``` Opens the specified org (identified by username or alias) in your browser. Because you’ve successfully authenticated with this org previously using the `org login web` Salesforce CLI command, it’s not required to provide your credentials again. **Display the Access Token for My Org** ```nolang sf org display --target-org ``` Output includes your access token, client ID, connected status, org ID, instance URL, username, and alias, if applicable. **Set an Alias for My Username** For convenience, create an alias for your username so that you don’t have to enter the entire Salesforce string. For example, instead of ```nolang juliet.capulet@empathetic-wolf-g5qddtr.com ``` Create an alias like ```nolang dev ``` To set the alias in this example, run ```nolang sf alias set dev juliet.capulet@empathetic-wolf-g5qddtr.com ``` **Use These Commands in a Script** Use the CLI’s JSON output by invoking the `--json` flag. Requesting JSON output provides a consistent output format, which is ideal for running scripts. Without the `--json` flag, the CLI can change the output format. **See Also** - [Salesforce CLI Setup Guide](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_intro.htm) - [Salesforce CLI Command Reference](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_unified.htm) # Step 2: Create a PushTopic Use the Developer Console to create the PushTopic record that contains a SOQL query. Event notifications are generated for updates that match the query. 1. Open the Developer Console. 2. Click **Debug** | **Open Execute Anonymous Window**. 3. In the Enter Apex Code window, paste in the following Apex code, and click **Execute**. ```apex PushTopic pushTopic = new PushTopic(); pushTopic.Name = 'InvoiceStatementUpdates'; pushTopic.Query = 'SELECT Id, Name, Status__c, Description__c FROM Invoice_Statement__c'; pushTopic.ApiVersion = 68.0; pushTopic.NotifyForOperationCreate = true; pushTopic.NotifyForOperationUpdate = true; pushTopic.NotifyForOperationUndelete = true; pushTopic.NotifyForOperationDelete = true; pushTopic.NotifyForFields = 'Referenced'; insert pushTopic; ``` **note:** If your organization has a namespace prefix defined, then you’ll need to preface the custom object and field names with that namespace when you define the PushTopic query. For example, `SELECT Id, Name, namespace__Status__c, namespace__Description__c FROM namespace__Invoice_Statement__c`. Because `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete` and `NotifyForOperationUndelete` are set to `true`, Streaming API evaluates records that are created, updated, deleted, or undeleted and generates a notification if the record matches the PushTopic query. Because `NotifyForFields` is set to `Referenced`, Streaming API will use fields in both the SELECT clause and the WHERE clause to generate a notification. Whenever the fields `Name`, `Status__c`, or `Description__c` are updated, a notification will be generated on this channel. For more information about `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete`, `NotifyForOperationUndelete`, and `NotifyForFields`, see [Event Notification Rules](https://developer.salesforce.com/docs/platform/api-streaming/using/events-and-notifications/event-notification-rules-intro.md). **note:** In API version 28.0 and earlier, notifications are only generated when records are created or updated. The `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete`, and `NotifyForOperationUndelete` fields are unavailable and the `NotifyForOperations` enum field is used instead to set which record events generate a notification. For more information see [PushTopic](https://developer.salesforce.com/docs/platform/api-streaming/reference/objects/pushtopic.md). # Step 2: Create a PushTopic (Legacy) Create a PushTopic in the Developer Console. Event notifications are generated for updates that match the query. **important:** PushTopic events is a legacy product. Salesforce no longer enhances PushTopic events with new features and provides limited support for this product. Instead of PushTopic events, consider using Change Data Capture events. To subscribe to change events, see [Java Quick Start for Pub/Sub API](https://developer.salesforce.com/docs/platform/pub-sub-api/guide/qs-java-quick-start.html) in the *Pub/Sub API Guide*. To learn about Change Data Capture, see the [*Change Data Capture Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm) and the [Change Data Capture Basics](https://trailhead.salesforce.com/content/learn/modules/change-data-capture) Trailhead module. 1. Open the Developer Console. 2. Click **Debug** | **Open Execute Anonymous Window**. 3. In the Enter Apex Code window, paste in the following Apex code, and click **Execute**. ```apex PushTopic pushTopic = new PushTopic(); pushTopic.Name = 'InvoiceStatementUpdates'; pushTopic.Query = 'SELECT Id, Name, Status__c, Description__c FROM Invoice_Statement__c'; pushTopic.ApiVersion = 68.0; pushTopic.NotifyForOperationCreate = true; pushTopic.NotifyForOperationUpdate = true; pushTopic.NotifyForOperationUndelete = true; pushTopic.NotifyForOperationDelete = true; pushTopic.NotifyForFields = 'Referenced'; insert pushTopic; ``` **note:** If your organization has a namespace prefix defined, then you’ll need to preface the custom object and field names with that namespace when you define the PushTopic query. For example, `SELECT Id, Name, namespace__Status__c, namespace__Description__c FROM namespace__Invoice_Statement__c`. Because `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete` and `NotifyForOperationUndelete` are set to `true`, Streaming API evaluates records that are created, updated, deleted, or undeleted and generates a notification if the record matches the PushTopic query. Because `NotifyForFields` is set to `Referenced`, Streaming API will use fields in both the SELECT clause and the WHERE clause to generate a notification. Whenever the fields `Name`, `Status__c`, or `Description__c` are updated, a notification will be generated on this channel. For more information about `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete`, `NotifyForOperationUndelete`, and `NotifyForFields`, see [Event Notification Rules](https://developer.salesforce.com/docs/platform/api-streaming/using/events-and-notifications/event-notification-rules-intro.md). **note:** In API version 28.0 and earlier, notifications are only generated when records are created or updated. The `NotifyForOperationCreate`, `NotifyForOperationUpdate`, `NotifyForOperationDelete`, and `NotifyForOperationUndelete` fields are unavailable and the `NotifyForOperations` enum field is used instead to set which record events generate a notification. For more information see [PushTopic](https://developer.salesforce.com/docs/platform/api-streaming/reference/objects/pushtopic.md). # Step 2: Generate or Obtain the Web Service WSDL To access the Lightning Platform Web service, you need a Web Service Description Language (WSDL) file. The WSDL file defines the Web service that is available to you. Your development platform uses this WSDL to generate an API to access the Lightning Platform Web service it defines. You can either obtain the WSDL file from your organization’s Salesforce administrator or you can generate it yourself if you have access to the WSDL download page in the Salesforce user interface. You can navigate to the most recent WSDL for your organization from Setup by entering `API` in the Quick Find box, then selecting **API**. For more information about WSDL, see [http://www.w3.org/TR/wsdl](http://www.w3.org/TR/wsdl). ## Generating the WSDL File for Your Organization Any user with the Modify All Data permission can download the Web Services Description Language (WSDL) file to integrate and extend Salesforce using the API. (The System Administrator profile has this permission.) The WSDL file is dynamically generated based on which type of WSDL file (enterprise or partner) you download. The generated WSDL defines all of the API calls, objects (including standard and custom objects), and fields that are available for API access for your organization. To generate the WSDL file for your organization: 1. Log in to your Enterprise, Unlimited, Performance, or Developer Edition Salesforce account. You must log in as an administrator or as a user who has the “Modify All Data” permission. Logins are checked to ensure they are from a known IP address. For more information, see [Security and the API](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_concepts_security.htm). 2. From Setup, enter `API` in the Quick Find box, then select **API** to display the WSDL download page. 3. Download the [appropriate WSDL](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-intro.md#choosing-a-wsdl): see [Download API WSDL and Client Certificates](https://help.salesforce.com/s/articleView?id=platform.dev_wsdl.htm#dev_wsdl/options_download_wsdl&type=5). # Step 2. Creating an External Client App Once you’ve registered your mobile app with the OS vendor’s push service, the next step is to create an external client app in Salesforce. | Required Editions | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Available in: Lightning Experience | | External Client Apps can be created in: **Group**, **Professional**, **Enterprise**, **Essentials**, **Performance**, **Unlimited**, and **Developer** Editions External Client Apps can be installed in: **All** Editions | | User Permissions Needed | | | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | To read, create, update, or delete connected apps: | Customize Application AND either Modify All Data OR Create, edit, and delete External Client Apps | | To update all fields except Profiles, Permission Sets, and Service Provider SAML Attributes: | Customize Application AND either Modify All Data OR Create, edit, and delete External Client Apps | | To update Profiles, Permission Sets, and Service Provider SAML Attributes: | Customize Application AND Modify All Data AND Manage Profiles and Permission Sets | | To rotate the consumer key and consumer secret: | Allow consumer key and secret rotation | | To install and uninstall connected apps: | Customize Application AND either Modify All Data OR Create, edit, and delete External Client Apps | | To install and uninstall packaged connected apps: | Customize Application AND either Modify All Data OR Create, edit, and delete External Client Apps AND Download AppExchange Packages | **note:** Connected apps creation is restricted as of Spring ‘26. You can continue to use existing connected apps during and after Spring ‘26. However, we recommend using [external client apps](https://help.salesforce.com/s/articleView?id=xcloud.external_client_apps.htm) instead. If you must continue creating connected apps, contact Salesforce Support. See [New connected apps can no longer be created in Spring ‘26](https://help.salesforce.com/s/articleView?id=005228017) for more details. Use the Salesforce external client app to provide the registration certificate or token of your mobile client app so that Salesforce can send push notifications. Also, the external client app provides the unique API name that identifies the mobile app to send notifications to. - **[Create an External Client App for Android](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-create-external-client-app-android.md)** - **[Create an External Client App for Apple iOS](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-create-external-client-app-apple.md)** - **[Testing Your External Client App Push Configuration](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-test-conn-app-push.md)** To run a quick test of your push notification setup, use the Send Test Notification page. Troubleshoot round-trip push notifications in a synchronous mechanism without having to configure custom notification types, Apex calls, or REST calls. You can also gain insights into what’s going on behind the scenes in the asynchronous environment of real-world push notifications. # Step 3: Bulk Insert This Bulk API 2.0 example guides you through creating a job, uploading data for the job, notifying Salesforce servers that your upload(s) are complete, checking the status of the processing job, and retrieving the results. To do any Bulk API 2.0 task, such as inserting or updating records, you first create a Bulk API 2.0 job. The job specifies the type of object that you’re loading, such as Account, and the operation that you’re performing, such as insert or delete. After you create the job, you use the resulting job ID in subsequent requests to upload job data or abort (cancel) the job. 1. Copy this CSV formatted list of accounts into a file named bulkinsert.csv. You use this file to upload data after creating the job. **note:** Save all files in this example in your terminal’s current working directory. The first row of the CSV file lists the field names for the object that you’re working with. Each subsequent row corresponds to a record that you want to insert. ```nolang Name,ShippingCity,NumberOfEmployees,AnnualRevenue,Website,Description Lorem Ipsum,Milano,2676,912260031,https://ft.com/lacus/at.jsp,"Lorem ipsum dolor sit amet" Posuere Inc,Bodø,141603,896852810,http://webs.com/in/faucibus/orci/luctus/et/ultrices/posuere.json,"consectetur adipiscing elit" Angeles Urban,Aykol,197724,257060529,http://odnoklassniki.ru/sapien.aspx,"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" Madaline Neubert Shoes,Xukou,190305,71664061,https://blogs.com/faucibus/orci/luctus/et/ultrices/posuere/cubilia.json,"Ut enim ad minim veniam" Times Online UK,Varadero,121802,58284123,http://timesonline.co.uk/eu/magna.html,"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat" The Washington Post,Hengdaohezi,190944,164329406,http://washingtonpost.com/vestibulum/proin/eu/mi/nulla/ac/enim.png,"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur" Amazon,Quintães,80285,684173825,http://amazon.co.uk/potenti/cras/in/purus/eu.png,"Excepteur sint occaecat cupidatat non proident" ``` 2. Create a job. 1. Create a file named `newinsertjob.json`. 2. Copy this content into the file. ```nolang { "object" : "Account", "contentType" : "CSV", "operation" : "insert", "lineEnding" : "LF" } ``` When you create a Bulk API 2.0 job, specify a line ending that matches the line ending used to create the CSV file using the `lineEnding` request field. Bulk API 2.0 supports two line-ending formats: linefeed (`LF`), and carriage-return plus linefeed (`CRLF`). The default line ending, if not specified, is `LF`. Different operating systems use different characters to mark the end of a line. Unix / Linux / OS X uses `LF` (line feed, '`\n`', `0x0A`). Windows / DOS uses `CRLF` (carriage return followed by line feed, '`\r\n`', `0x0D0A`). It’s also possible that the text editor used to create the CSV file is configured for a specific line-ending format that supersedes the default operating system format. **URI** ```nolang /services/data/v68.0/jobs/ingest/ ``` **Example for creating a bulk insert job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json" -H "Accept: application/json" -H "X-PrettyPrint:1" -d @newinsertjob.json -X POST ``` **Example response body** The response includes the job `id`, with a job `state` of `Open`. ```nolang { "id" : "7505fEXAMPLE4C2AAM",​ "operation" : "insert",​ "object" : "Account",​ "createdById" : "0055fEXAMPLEtG4AAM",​ "createdDate" : "2022-01-02T21:33:43.000+0000",​ "systemModstamp" : "2022-01-02T21:33:43.000+0000",​ "state" : "Open",​ "concurrencyMode" : "Parallel",​ "contentType" : "CSV",​ "apiVersion" : 68.0,​ "contentUrl" : "services/data/68.0/jobs/ingest/7505fEXAMPLE4C2AAM/batches",​ "lineEnding" : "LF",​ "columnDelimiter" : "COMMA" } ``` You use the job `id` from this response in the next steps. You can also use the URI in the `contentUrl` field in the next step when you upload your data. 3. Upload your CSV data using the URI in the `contentUrl` field of the response. You can upload up to 150 MB per job (after base64 encoding). The URI is similar to ```nolang /services/data/v68.0/jobs/ingest/jobId/batches/ ``` **Example for uploading data** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7505fEXAMPLE4C2AAM/batches/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: text/csv" -H "Accept: application/json" -H "X-PrettyPrint:1" --data-binary @bulkinsert.csv -X PUT ``` **Example response body** No response body. 4. Set job `state` to `UploadComplete`. After you’re done submitting data, notify Salesforce servers that the upload of job data is complete and is ready for processing. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/ ``` **Example of setting `state` to `UploadComplete`** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7505fEXAMPLE4C2AAM/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json; charset=UTF-8" -H "Accept: application/json" -H "X-PrettyPrint:1" --data-raw '{ "state" : "UploadComplete" }' -X PATCH ``` **Example response body** ```nolang { "id" : "7505fEXAMPLE4C2AAM",​ "operation" : "insert",​ "object" : "Account",​ "createdById" : "0055fEXAMPLEtG4AAM",​ "createdDate" : "2022-01-02T21:33:43.000+0000",​ "systemModstamp" : "2022-01-02T21:33:43.000+0000",​ "state" : "UploadComplete",​ "concurrencyMode" : "Parallel",​ "contentType" : "CSV",​ "apiVersion" : 68.0 } ``` 5. Check the job status and results. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/ ``` **Example of checking job status** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7505fEXAMPLE4C2AAM/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Accept: application/json" -H "X-PrettyPrint:1" -X GET ``` **Example response body** ```nolang { "id" : "7505fEXAMPLE4C2AAM",​ "operation" : "insert",​ "object" : "Account",​ "createdById" : "0055fEXAMPLEtG4AAM",​ "createdDate" : "2022-01-02T21:33:43.000+0000",​ "systemModstamp" : "2022-01-02T21:38:31.000+0000",​ "state" : "JobComplete",​ "concurrencyMode" : "Parallel",​ "contentType" : "CSV",​ "apiVersion" : 68.0,​ "jobType" : "V2Ingest",​ "lineEnding" : "LF",​ "columnDelimiter" : "COMMA",​ "numberRecordsProcessed" : 7,​ "numberRecordsFailed" : 0,​ "retries" : 0,​ "totalProcessingTime" : 886,​ "apiActiveProcessingTime" : 813,​ "apexProcessingTime" : 619 } ``` 6. Get successful results. After a job is in the `JobComplete` or `Failed` state, you can get details about which records were successfully processed. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/successfulResults/ ``` **Example of getting successful results** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7505fEXAMPLE4C2AAM/successfulResults/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json" -H "Accept: text/csv" -H "X-PrettyPrint:1" -X GET ``` The response contains CSV formatted data, with each row containing a record ID (`sf__Id`) and information on whether that record was successfully processed or not (`sf__Created`). **Example response body** ```nolang "sf__Id","sf__Created",Name,ShippingCity,NumberOfEmployees,AnnualRevenue,Website,Description "0018c00002FInboAAD","true","Lorem Ipsum","Milano","2676","9.12260031E8","https://ft.com/lacus/at.jsp","Lorem ipsum dolor sit amet" "0018c00002FInbpAAD","true","Posuere Inc","Bodø","141603","8.9685281E8","http://webs.com/in/faucibus/orci/luctus/et/ultrices/posuere.json","consectetur adipiscing elit" "0018c00002FInbqAAD","true","Angeles Urban","Aykol","197724","2.57060529E8","http://odnoklassniki.ru/sapien.aspx","sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" "0018c00002FInbrAAD","true","Madaline Neubert Shoes","Xukou","190305","7.1664061E7","https://blogs.com/faucibus/orci/luctus/et/ultrices/posuere/cubilia.json","Ut enim ad minim veniam" "0018c00002FInbsAAD","true","Times Online UK","Varadero","121802","5.8284123E7","http://timesonline.co.uk/eu/magna.html","quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat" "0018c00002FInbtAAD","true","The Washington Post","Hengdaohezi","190944","1.64329406E8","http://washingtonpost.com/vestibulum/proin/eu/mi/nulla/ac/enim.png","Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur" "0018c00002FInbuAAD","true","Amazon","Quintães","80285","6.84173825E8","http://amazon.co.uk/potenti/cras/in/purus/eu.png","Excepteur sint occaecat cupidatat non proident" ``` To get details about records that encountered an error during processing, use a GET request using the `failedResults` resource. To make sure that you’re looking at the complete result set, look at unprocessed records by using the `unprocessedRecords` resource. See [Get Job Unprocessed Record Results](https://developer.salesforce.com/docs/platform/api-asynch/reference/get-job-unprocessed-results.md). # Step 3: Create the Static Resources 1. Download this static resource .zip file: [streaming_api_interactive_visualforce_demo-v40.zip](https://resources.docs.salesforce.com/rel1/doc/en-us/static/misc/streaming_api_interactive_visualforce_demo-v40.zip) 2. Extract the following files from the .zip fle: |File Name|Description| |---------|-----------| |cometd.zip|Files for CometD version 3.1.0 and the Dojo toolkit used by demo.js. When you define a .zip archive file as a static resource, Visualforce can access the files in that archive. The .zip file becomes a virtual file system.| |demo.css|The CSS code that formats the Visualforce page.| |demo.js|The code used by the page to subscribe to the channel, receive and display the notifications, and unsubscribe from the channel.| |json2.js|The JavaScript library that contains the `stringify` and `parse` methods.| |StreamingApiDemo|The Visualforce page that displays the Streaming API notifications.| 3. From Setup, enter `Static Resources` in the `Quick Find` box, then select **Static Resources** to add the extracted files with the following names: |File Name|Static Resource Name| |---------|--------------------| |cometd.zip|cometd_zip| |demo.css|demo_css| |demo.js|demo_js| |json2.js|json2_js| # Step 3: Download and Build the Project Before you can run the connector examples, download the Java source files and build the Java project. **Prerequisites:** - Java Development Kit 8 or later (see [Java Downloads](http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html)) - Eclipse IDE for Java Developers (get a recent version from [http://www.eclipse.org/downloads/eclipse-packages/](http://www.eclipse.org/downloads/eclipse-packages/)). This example walks you through the steps of building the project with the Eclipse IDE but you can you use your preferred IDE to build the Java client. The EMP Connector project includes examples in the [GitHub repository’s example folder ](https://github.com/forcedotcom/EMP-Connector/tree/master/src/main/java/com/salesforce/emp/connector/example) that use the connector to log in and subscribe to events. In the next steps, you run the following examples locally on your system. - [LoginExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/LoginExample.java) - [BearerTokenExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/BearerTokenExample.java) **note:** LoginExample.java logs in to your Developer Edition org instance using the instanced login URL such as https://na139.salesforce.com. To pass in a different login URL, such as your org’s My Domain login URL for production or a sandbox, use [DevLoginExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/DevLoginExample.java) instead. We recommend using DevLoginExample.java because My Domain login URLs provide an extra layer of security. DevLoginExample.java also provides debug logging for the Bayeux messages received. To download and build the EMP connector project: 1. To download the project files, do one of the following. - Clone the EMP-Connector project using git. ```nolang git clone https://github.com/forcedotcom/EMP-Connector ``` - Download the project zip file from GitHub, and then extract the zip to a local folder. 2. In Eclipse, import the Maven project from the folder where you cloned or extracted the project. The dependencies that are specified in the Maven’s pom.xml file, such as CometD, are added in the Java project in Eclipse. 3. If the Java project wasn’t automatically built, build it. If you prefer to run the tool from the command line, generate the JAR file using the Maven command `mvn clean package`. The generated JAR file includes the connector and the example class functionality. The JAR file is a shaded JAR—it contains all dependencies for the connector, so you don’t have to download them separately. The JAR file has a `-phat` Maven classifier. You can run the login example from the command line. To run the tool against a Developer Edition org instance without specifying a login URL, use this command, which uses the LoginExample.java class by default. ```nolang $ java -jar target/emp-connector-0.0.1-SNAPSHOT-phat.jar [optional_replay_id] ``` To specify a different login URL, such as your org’s My Domain login URL, use this command, which references the DevLoginExample.java class. ```nolang $ java -classpath target/emp-connector-0.0.1-SNAPSHOT-phat.jar com.salesforce.emp.connector.example.DevLoginExample [optional_replayId] ``` For \, use your org’s My Domain login URL, including the https:// prefix. For example, `https://MyDomainName.my.salesforce.com`. **Open Source Project** EMP Connector is an open-source project, so you can contribute to it with your own enhancements by submitting pull requests to the repository. # Step 3: Import the WSDL File Into Your Development Platform After you have the WSDL file, import it into your development platform so that your development environment can generate the necessary objects for use in building client Web service applications in that environment. This section provides sample instructions for WSC and Microsoft Visual Studio. For instructions about other development platforms, see your platform's product documentation. **note:** The process for importing WSDL files is identical for the enterprise and partner WSDL files. ## Instructions for Java Environments (WSC) Java environments access the API through Java objects that serve as proxies for their server-side counterparts. Before using the API, you must first generate these objects from your organization's WSDL file. Each SOAP client has its own tool for this process. For WSC, use the `wsdlc` utility. **note:** Before you run `wsdlc`, you must have the WSC JAR file installed on your system and referenced in your classpath. The basic syntax for `wsdlc` is: ```java java -classpath pathToJAR/force-wsc-XX.X.X-uber.jar com.sforce.ws.tools.wsdlc pathToWsdl/WsdlFilename​ pathToOutputJar/OutputJarFilename ``` This command generates an output jar file based on the specified WSDL file. After the output jar file is created, reference it along with the WSC .jar file (for example, `force-wsc-57.0.0-uber.jar`) in your Java program to create a client application. ## Instructions for Microsoft Visual Studio Visual Studio languages access the API through objects that serve as proxies for their server-side counterparts. Before using the API, you must first generate these objects from your organization's WSDL file. After you have the proxy classes for the server-side objects, ensure that you specify whether you have set any values on non-string fields. For more information, see [Implementation Considerations](https://developer.salesforce.com/docs/platform/api/concepts/implementation-considerations.md#net-non-string-fields-and-the-enterprise-wsdl). Visual Studio provides two approaches for importing your WSDL file and generating an XML Web service client: an IDE-based approach and a command-line approach. This walkthrough describes how to import your WSDL file through the IDE. **note:** Before you begin, the first step is to create an application or open an existing application in Visual Studio. In addition, you need the generated WSDL file, as described in [Generating the WSDL File for Your Organization](https://developer.salesforce.com/docs/platform/api/guide/sforce-api-quickstart-steps-generate-wsdl.md). An XML Web service client is any component or application that references and uses an XML Web service. It isn’t necessarily a client-based application. In fact, in many cases, your XML Web service clients can be other Web applications, such as Web Forms or even other XML Web services. When accessing XML Web services in managed code, a proxy class and the .NET Framework handle all of the infrastructure coding. To access an XML Web service from managed code: 1. Name your project `Walkthrough` or change the `using` directive in the following sample to _`your_project_name.web_reference_name`_. Then, add a Web reference to your project for the XML Web service that you want to access. The Web reference creates a proxy class with methods that serve as proxies for each exposed method of the XML Web service. 2. Add the namespace for the Web reference. 3. Create an instance of the proxy class and then access the methods of that class as you would the methods of any other class. You can add either a .NET 2.0 style Web reference or a .NET 3.0 style Service reference, depending on your version of Visual Studio and preferred developer environment. A .NET 3.0 style reference uses services like SoapClient instead of SforceService. To add a Web reference: **note:** These steps are different depending on the version of Visual Studio that you're using. For more information, see _Adding and Removing Web References_ in the Visual Studio documentation. 1. In the Project menu, select **Add Service Reference**, select **Advanced**, and then select **Add Web Reference**. 2. In the URL box of the Add Web Reference dialog box, type the URL to obtain the service description of the XML Web service you want to access, such as: C:\WSDLFiles\enterprise.wsdl 3. To retrieve information about the XML Web service, click **Go**. 4. In the Web reference name box, rename the Web reference to `sforce`, which is the name you use for this Web reference. 5. To add a Web reference for the target XML Web service, click **Add Reference**. 6. Visual Studio retrieves the service description and generates a proxy class to interface between your application and the XML Web service. **note:** If you’re using Visual Basic .Net 1.1 and the enterprise WSDL, modify the generated Web service client to overcome a bug in Visual Studio's client generation utility. The API exposes two objects ( [Case](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_case.htm) and [Event](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_event.htm)) whose names conflict with Visual Basic keywords. When the classes that represent these objects are created, Visual Studio wraps the class names with brackets (`[Case]` and `[Event]`). This is the method by which you can reuse keywords. Unfortunately, in the definition of the `SObject` class, Visual Studio doesn’t wrap Case and Event to class references in the `System.Xml.Serialization.XmlIncludeAttribute` that are part of the `SObject` definition. To work around this problem in Visual Studio, edit the `XmlIncludeAttribute` settings for Case and Event, as shown in the example. These edits don’t apply to C# and only apply when using the enterprise version of the WSDL. ```nolang System.Xml.Serialization.XmlIncludeAttribute(GetType([Event])), _ System.Xml.Serialization.XmlIncludeAttribute(GetType([Case])), _ ``` # Step 3. Configure Your Mobile SDK App In your Mobile SDK app, implement push notification protocols required by Salesforce and the device OS provider. Follow the instructions for your target mobile platform (Android, iOS, or hybrid). - **[Enable Push Notifications in a Salesforce Mobile SDK Android App](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-client-app-android.md)** Perform these steps in your Android Mobile SDK app to receive push notifications. - **[Enable Push Notifications in a Salesforce Mobile SDK iOS App](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-client-app-ios.md)** Perform these steps in your iOS Mobile SDK app to receive push notifications. - **[Enable Push Notifications in a Salesforce Mobile SDK Hybrid App](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-client-app-hybrid.md)** Perform these steps in your hybrid Mobile SDK app to receive push notifications. - **[Handle Notification Encryption in Salesforce Mobile SDK Apps](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-encrypted-notifications.md)** Mobile notifications travel from Salesforce, through third-party messaging services to mobile carriers, then on to mobile devices. Such an indirect path only increases the opportunities for malicious attacks. To guard against snooping or hacking, Salesforce encrypts Notification Builder notifications. Your app is responsible for decrypting these notifications. - **[Build Your Own In-App Notification Feature](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-in-app-tray.md)** If you use the Salesforce mobile app, you’re familiar with the Salesforce Bell. The Bell provides an in-app notification tray that lists the current user’s most recent notifications. With Salesforce Notification APIs, you can design and build your own tray. # Step 4: Bulk Insert with a Multipart Request This Bulk API 2.0 example guides you through creating a job, uploading data for the job, checking the status, and retrieving the results. This example uses a single, multipart request to create the job and upload the data. In this example, `BOUNDARY` is used at the start, middle, and end of the file to mark the request body boundaries between the job’s details and its CSV data. 1. Copy this multipart, JSON-formatted content into a file named `newmultipartjob.json`. **note:** Save all files in this example in your terminal’s current working directory. ```nolang --BOUNDARY Content-Type: application/json Content-Disposition: form-data; name="job" { "object":"Contact", "contentType":"CSV", "operation": "insert", "lineEnding" : "LF" } --BOUNDARY Content-Type: text/csv Content-Disposition: form-data; name="content"; filename="content" FirstName,LastName,MailingCity Astro,Nomical,San Francisco Hootie,McOwl,San Francisco Appy,Camper,San Francisco Earnie,Badger,San Francisco --BOUNDARY-- ``` 2. Create a job. **URI** ```nolang /services/data/v68.0/jobs/ingest/ ``` **Example of creating a job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v67.0/jobs/ingest/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: multipart/form-data; boundary=\"BOUNDARY\"" -H "Accept: application/json" -H "X-PrettyPrint:1" --data-binary @newmultipartjob.json -X POST ``` The response includes the job `id`, with a job `state` of `UploadComplete`. You use the job `id` in the next steps. **Example response body** ```nolang { "id" : "7303gEXAMPLE4X2QAN", "operation" : "insert", "object" : "Contact", "createdById" : "0055fEXAMPLEtG4AAM", "createdDate" : "2022-01-02T19:26:52.000+0000", "systemModstamp" : "2022-01-02T19:26:52.000+0000", "state" : "UploadComplete", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 68.0, "lineEnding" : "LF", "columnDelimiter" : "COMMA" } ``` After you create a multipart job, the upload is completed for you automatically. You don’t need to manually set the job `state` to `UploadComplete` for a multipart job. 3. Check the job status and results with this URI. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/ ``` **Example of checking job status and results** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7303gEXAMPLE4X2QAN/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Accept: application/json" -H "X-PrettyPrint:1" -X GET ``` **Example response body** ```nolang { "id" : "7303gEXAMPLE4X2QAN", "operation" : "insert", "object" : "Contact", "createdById" : "0055fEXAMPLEtG4AAM", "createdDate" : "2022-01-02T19:54:04.000+0000", "systemModstamp" : "2022-01-02T19:54:05.000+0000", "state" : "JobComplete", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 67.0, "jobType" : "V2Ingest", "lineEnding" : "LF", "columnDelimiter" : "COMMA", "numberRecordsProcessed" : 4, "numberRecordsFailed" : 0, "retries" : 0, "totalProcessingTime" : 50, "apiActiveProcessingTime" : 6, "apexProcessingTime" : 0 } ``` 4. Get successful results. After a job is in the `JobComplete` or `Failed` state, you can get details about which records were successfully processed. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/successfulResults/ ``` **Example of getting successful results** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7303gEXAMPLE4X2QAN/successfulResults/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json" -H "Accept: text/csv" -H "X-PrettyPrint:1" -X GET ``` **Example response body** ```nolang "sf__Id","sf__Created",FirstName,LastName,MailingCity "0038c00002hMS4kAAG","true","Astro","Nomical","San Francisco" "0038c00002hMS4lAAG","true","Hootie","McOwl","San Francisco" "0038c00002hMS4mAAG","true","Appy","Camper","San Francisco" "0038c00002hMS4nAAG","true","Earnie","Badger","San Francisco" ``` To get details about records that encountered an error during processing, use a GET request with the `failedResults` resource. To make sure that you’re looking at the complete result set, look at unprocessed records by using the `unprocessedRecords` resource. See [Get Job Unprocessed Record Results](https://developer.salesforce.com/docs/platform/api-asynch/reference/get-job-unprocessed-results.md). # Step 4: Create a Visualforce Page Create a Visualforce page to display the channel notifications. 1. From Setup, enter `Visualforce Pages` in the `Quick Find` box, then select **Visualforce Pages**. 2. Click **New**. 3. In the **Label** field, enter the name of the page StreamingAPIDemo. 4. Replace the code in the page with the code from the StreamingApiDemo file that you downloaded. ```apex_code
      Enter Topic Name
    ``` 5. Click **Save** to save the page. # Step 4: Use the Connector with Username and Password Login Now that you’ve downloaded and built EMP Connector, use it to connect to CometD and subscribe to the PushTopic. Let’s run an example that uses username and password login. 1. In the /src/main/java/com/salesforce/emp/connector/example folder, open the [LoginExample.java](https://github.com/forcedotcom/EMP-Connector/blob/master/src/main/java/com/salesforce/emp/connector/example/LoginExample.java) source file. 2. Run the `LoginExample` class and provide arguments. 1. In Package Explorer, navigate to the LoginExample.java file. Right-click the file, and select **Run As** | **Run Configurations**. 2. On the Arguments tab, add values for the following arguments, separated by a space.
    Argument Value
    username Username of the logged-in user
    password Password for the username (or logged-in user)
    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

    3. Click **Run**. The sample is now subscribed to the event channel and is listening to event notifications. As soon as an event notification is published and received, the tool prints it to the console. 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.}} ``` **note:** 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. Generally, don’t handle usernames and passwords of others when running code in production. In a production environment, delegate the login to OAuth. The next step connects to Streaming API with OAuth. # Step 4: Walk Through the Sample Code Once you have imported your WSDL file, you can begin building client applications that use the API. Use the following samples to create a basic client application. Comments embedded in the sample explain each section of code. ## Java Sample Code This section walks through a sample Java client application that uses the WSC SOAP client. The purpose of this sample application is to show the required steps for logging into the login server and to demonstrate the invocation and subsequent handling of several API calls. To run this sample, you must pass the authentication endpoint URL as an argument for your program. You can obtain this URL from the WSDL file. This sample application performs the following main tasks: 1. Prompts the user for their Salesforce username and password. 2. Calls [`login()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login.md) to log in to the single login server and, if the login succeeds, retrieves user information and writes it to the console along with session information. 3. Calls [`describeGlobal()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-describeglobal.md) to retrieve a list of all available objects for the organization’s data. The `describeGlobal` method determines [the objects that are available to the logged in user](https://developer.salesforce.com/docs/platform/api/calls/calls.md). This call should not be made more than once per session, since the data returned from the call is not likely to change frequently. The [DescribeGlobalResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-describeglobal-describeglobalresult.md) is echoed to the console. 4. Calls [`describeSObjects()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-describesobjects.md) to retrieve metadata (field list and object properties) for a specified object. The `describeSObject` method illustrates the type of metadata information that can be obtained for each object available to the user. The sample client application executes a `describeSObjects()` call on the object that the user specifies and then echoes the returned metadata information to the console. Object metadata information includes permissions, field types and lengths, and available values for picklist fields and types for `referenceTo` fields. 5. Calls [`query()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query.md), passing a simple query string `("SELECT FirstName, LastName FROM Contact")`, and iterating through the returned [QueryResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query-queryresult.md). 6. Calls [`logout()`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-logout.md) to the log the user out. The following sample code uses try/catch blocks to handle exceptions that might be thrown by the API calls. ```class package com.example.samples; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.IOException; import com.sforce.soap.enterprise.DeleteResult; import com.sforce.soap.enterprise.DescribeGlobalResult; import com.sforce.soap.enterprise.DescribeGlobalSObjectResult; import com.sforce.soap.enterprise.DescribeSObjectResult; import com.sforce.soap.enterprise.EnterpriseConnection; import com.sforce.soap.enterprise.Error; import com.sforce.soap.enterprise.Field; import com.sforce.soap.enterprise.FieldType; import com.sforce.soap.enterprise.GetUserInfoResult; import com.sforce.soap.enterprise.LoginResult; import com.sforce.soap.enterprise.PicklistEntry; import com.sforce.soap.enterprise.QueryResult; import com.sforce.soap.enterprise.SaveResult; import com.sforce.soap.enterprise.sobject.Account; import com.sforce.soap.enterprise.sobject.Contact; import com.sforce.soap.enterprise.sobject.SObject; import com.sforce.ws.ConnectorConfig; import com.sforce.ws.ConnectionException; public class QuickstartApiSample { private static BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); EnterpriseConnection connection; String authEndPoint = ""; public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: com.example.samples." + "QuickstartApiSamples "); System.exit(-1); } QuickstartApiSample sample = new QuickstartApiSample(args[0]); sample.run(); } public void run() { // Make a login call if (login()) { // Do a describe global describeGlobalSample(); // Describe an object describeSObjectsSample(); // Retrieve some data using a query querySample(); // Log out logout(); } } // Constructor public QuickstartApiSample(String authEndPoint) { this.authEndPoint = authEndPoint; } private String getUserInput(String prompt) { String result = ""; try { System.out.print(prompt); result = reader.readLine(); } catch (IOException ioe) { ioe.printStackTrace(); } return result; } private boolean login() { boolean success = false; String username = getUserInput("Enter username: "); String password = getUserInput("Enter password: "); try { ConnectorConfig config = new ConnectorConfig(); config.setUsername(username); config.setPassword(password); System.out.println("AuthEndPoint: " + authEndPoint); config.setAuthEndpoint(authEndPoint); connection = new EnterpriseConnection(config); printUserInfo(config); success = true; } catch (ConnectionException ce) { ce.printStackTrace(); } return success; } private void printUserInfo(ConnectorConfig config) { try { GetUserInfoResult userInfo = connection.getUserInfo(); System.out.println("\nLogging in ...\n"); System.out.println("UserID: " + userInfo.getUserId()); System.out.println("User Full Name: " + userInfo.getUserFullName()); System.out.println("User Email: " + userInfo.getUserEmail()); System.out.println(); System.out.println("SessionID: " + config.getSessionId()); System.out.println("Auth End Point: " + config.getAuthEndpoint()); System.out .println("Service End Point: " + config.getServiceEndpoint()); System.out.println(); } catch (ConnectionException ce) { ce.printStackTrace(); } } private void logout() { try { connection.logout(); System.out.println("Logged out."); } catch (ConnectionException ce) { ce.printStackTrace(); } } /** * To determine the objects that are available to the logged-in user, the * sample client application executes a describeGlobal call, which returns * all of the objects that are visible to the logged-in user. This call * should not be made more than once per session, as the data returned from * the call likely does not change frequently. The DescribeGlobalResult is * simply echoed to the console. */ private void describeGlobalSample() { try { // describeGlobal() returns an array of object results that // includes the object names that are available to the logged-in user. DescribeGlobalResult dgr = connection.describeGlobal(); System.out.println("\nDescribe Global Results:\n"); // Loop through the array echoing the object names to the console for (int i = 0; i < dgr.getSobjects().length; i++) { System.out.println(dgr.getSobjects()[i].getName()); } } catch (ConnectionException ce) { ce.printStackTrace(); } } /** * The following method illustrates the type of metadata information that can * be obtained for each object available to the user. The sample client * application executes a describeSObject call on a given object and then * echoes the returned metadata information to the console. Object metadata * information includes permissions, field types and length and available * values for picklist fields and types for referenceTo fields. */ private void describeSObjectsSample() { String objectToDescribe = getUserInput("\nType the name of the object to " + "describe (try Account): "); try { // Call describeSObjects() passing in an array with one object type // name DescribeSObjectResult[] dsrArray = connection .describeSObjects(new String[] { objectToDescribe }); // Since we described only one sObject, we should have only // one element in the DescribeSObjectResult array. DescribeSObjectResult dsr = dsrArray[0]; // First, get some object properties System.out.println("\n\nObject Name: " + dsr.getName()); if (dsr.getCustom()) System.out.println("Custom Object"); if (dsr.getLabel() != null) System.out.println("Label: " + dsr.getLabel()); // Get the permissions on the object if (dsr.getCreateable()) System.out.println("Createable"); if (dsr.getDeletable()) System.out.println("Deleteable"); if (dsr.getQueryable()) System.out.println("Queryable"); if (dsr.getReplicateable()) System.out.println("Replicateable"); if (dsr.getRetrieveable()) System.out.println("Retrieveable"); if (dsr.getSearchable()) System.out.println("Searchable"); if (dsr.getUndeletable()) System.out.println("Undeleteable"); if (dsr.getUpdateable()) System.out.println("Updateable"); System.out.println("Number of fields: " + dsr.getFields().length); // Now, retrieve metadata for each field for (int i = 0; i < dsr.getFields().length; i++) { // Get the field Field field = dsr.getFields()[i]; // Write some field properties System.out.println("Field name: " + field.getName()); System.out.println("\tField Label: " + field.getLabel()); // This next property indicates that this // field is searched when using // the name search group in SOSL if (field.getNameField()) System.out.println("\tThis is a name field."); if (field.getRestrictedPicklist()) System.out.println("This is a RESTRICTED picklist field."); System.out.println("\tType is: " + field.getType()); if (field.getLength() > 0) System.out.println("\tLength: " + field.getLength()); if (field.getScale() > 0) System.out.println("\tScale: " + field.getScale()); if (field.getPrecision() > 0) System.out.println("\tPrecision: " + field.getPrecision()); if (field.getDigits() > 0) System.out.println("\tDigits: " + field.getDigits()); if (field.getCustom()) System.out.println("\tThis is a custom field."); // Write the permissions of this field if (field.getNillable()) System.out.println("\tCan be nulled."); if (field.getCreateable()) System.out.println("\tCreateable"); if (field.getFilterable()) System.out.println("\tFilterable"); if (field.getUpdateable()) System.out.println("\tUpdateable"); // If this is a picklist field, show the picklist values if (field.getType().equals(FieldType.picklist)) { System.out.println("\t\tPicklist values: "); PicklistEntry[] picklistValues = field.getPicklistValues(); for (int j = 0; j < field.getPicklistValues().length; j++) { System.out.println("\t\tValue: " + picklistValues[j].getValue()); } } // If this is a foreign key field (reference), // show the values if (field.getType().equals(FieldType.reference)) { System.out.println("\tCan reference these objects:"); for (int j = 0; j < field.getReferenceTo().length; j++) { System.out.println("\t\t" + field.getReferenceTo()[j]); } } System.out.println(""); } } catch (ConnectionException ce) { ce.printStackTrace(); } } private void querySample() { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; try { QueryResult qr = connection.query(soqlQuery); boolean done = false; if (qr.getSize() > 0) { System.out.println("\nLogged-in user can see " + qr.getRecords().length + " contact records."); while (!done) { System.out.println(""); SObject[] records = qr.getRecords(); for (int i = 0; i < records.length; ++i) { Contact con = (Contact) records[i]; String fName = con.getFirstName(); String lName = con.getLastName(); if (fName == null) { System.out.println("Contact " + (i + 1) + ": " + lName); } else { System.out.println("Contact " + (i + 1) + ": " + fName + " " + lName); } } if (qr.isDone()) { done = true; } else { qr = connection.queryMore(qr.getQueryLocator()); } } } else { System.out.println("No records found."); } } catch (ConnectionException ce) { ce.printStackTrace(); } } } ``` ## C# Sample Code This section walks through a sample C# client application. The purpose of this sample application is to show the required steps for logging in and to demonstrate the invocation and subsequent handling of several API calls. This sample application performs the following main tasks: 1. Prompts the user for their Salesforce username and password. 2. Calls `login()` to log in to the single login server and, if the login succeeds: - Sets the returned [sessionId](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md) into the session header, which is required for session authentication on subsequent API calls. - Resets the Lightning Platform endpoint to the returned [`serverUrl`](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-login-loginresult.md), which is the target of subsequent API calls. All client applications that access the API must complete the tasks in this step before attempting any subsequent API calls. - Retrieves user information and writes it to the console along with session information. 3. Calls `describeGlobal()` to retrieve a list of all available objects for the organization’s data. The `describeGlobal` method determines the objects that are available to the logged in user. This call should not be made more than once per session, since the data returned from the call is not likely to change frequently. The [DescribeGlobalResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-describeglobal-describeglobalresult.md) is echoed to the console. 4. Calls `describeSObjects()` to retrieve metadata (field list and object properties) for a specified object. The `describeSObject` method illustrates the type of metadata information that can be obtained for each object available to the user. The sample client application executes a `describeSObjects()` call on the object that the user specifies and then echoes the returned metadata information to the console. Object metadata information includes permissions, field types and lengths, and available values for picklist fields and types for `referenceTo` fields. 5. Calls `query()`, passing a simple query string `("SELECT FirstName, LastName FROM Contact")`, and iterating through the returned [QueryResult](https://developer.salesforce.com/docs/platform/api/calls/sforce-api-calls-query-queryresult.md). 6. Calls `logout()` to the log the user out. The following sample code uses try/catch blocks to handle exceptions that might be thrown by the API calls. The following code begins the sample C# client application. ```class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Services.Protocols; using Walkthrough.sforce; namespace Walkthrough { class QuickstartApiSample { private SforceService binding; [STAThread] static void Main(string[] args) { QuickstartApiSample sample = new QuickstartApiSample(); sample.run(); } public void run() { // Make a login call if (login()) { // Do a describe global describeGlobalSample(); // Describe an account object describeSObjectsSample(); // Retrieve some data using a query querySample(); // Log out logout(); } } private bool login() { Console.Write("Enter username: "); string username = Console.ReadLine(); Console.Write("Enter password: "); string password = Console.ReadLine(); // Create a service object binding = new SforceService(); // Timeout after a minute binding.Timeout = 60000; // Try logging in LoginResult lr; try { Console.WriteLine("\nLogging in...\n"); lr = binding.login(username, password); } // ApiFault is a proxy stub generated from the WSDL contract when // the web service was imported catch (SoapException e) { // Write the fault code to the console Console.WriteLine(e.Code); // Write the fault message to the console Console.WriteLine("An unexpected error has occurred: " + e.Message); // Write the stack trace to the console Console.WriteLine(e.StackTrace); // Return False to indicate that the login was not successful return false; } // Check if the password has expired if (lr.passwordExpired) { Console.WriteLine("An error has occurred. Your password has expired."); return false; } /** Once the client application has logged in successfully, it will use * the results of the login call to reset the endpoint of the service * to the virtual server instance that is servicing your organization */ // Save old authentication end point URL String authEndPoint = binding.Url; // Set returned service endpoint URL binding.Url = lr.serverUrl; /** The sample client application now has an instance of the SforceService * that is pointing to the correct endpoint. Next, the sample client * application sets a persistent SOAP header (to be included on all * subsequent calls that are made with SforceService) that contains the * valid sessionId for our login credentials. To do this, the sample * client application creates a new SessionHeader object and persist it to * the SforceService. Add the session ID returned from the login to the * session header */ binding.SessionHeaderValue = new SessionHeader(); binding.SessionHeaderValue.sessionId = lr.sessionId; printUserInfo(lr, authEndPoint); // Return true to indicate that we are logged in, pointed // at the right URL and have our security token in place. return true; } private void printUserInfo(LoginResult lr, String authEP) { try { GetUserInfoResult userInfo = lr.userInfo; Console.WriteLine("\nLogging in ...\n"); Console.WriteLine("UserID: " + userInfo.userId); Console.WriteLine("User Full Name: " + userInfo.userFullName); Console.WriteLine("User Email: " + userInfo.userEmail); Console.WriteLine(); Console.WriteLine("SessionID: " + lr.sessionId); Console.WriteLine("Auth End Point: " + authEP); Console.WriteLine("Service End Point: " + lr.serverUrl); Console.WriteLine(); } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } } private void logout() { try { binding.logout(); Console.WriteLine("Logged out."); } catch (SoapException e) { // Write the fault code to the console Console.WriteLine(e.Code); // Write the fault message to the console Console.WriteLine("An unexpected error has occurred: " + e.Message); // Write the stack trace to the console Console.WriteLine(e.StackTrace); } } /** * To determine the objects that are available to the logged-in * user, the sample client application executes a describeGlobal * call, which returns all of the objects that are visible to * the logged-in user. This call should not be made more than * once per session, as the data returned from the call likely * does not change frequently. The DescribeGlobalResult is * simply echoed to the console. */ private void describeGlobalSample() { try { // describeGlobal() returns an array of object results that // includes the object names that are available to the logged-in user. DescribeGlobalResult dgr = binding.describeGlobal(); Console.WriteLine("\nDescribe Global Results:\n"); // Loop through the array echoing the object names to the console for (int i = 0; i < dgr.sobjects.Length; i++) { Console.WriteLine(dgr.sobjects[i].name); } } catch (SoapException e) { Console.WriteLine("An exception has occurred: " + e.Message + "\nStack trace: " + e.StackTrace); } } /** * The following method illustrates the type of metadata * information that can be obtained for each object available * to the user. The sample client application executes a * describeSObject call on a given object and then echoes * the returned metadata information to the console. Object * metadata information includes permissions, field types * and length and available values for picklist fields * and types for referenceTo fields. */ private void describeSObjectsSample() { Console.Write("\nType the name of the object to " + "describe (try Account): "); string objectType = Console.ReadLine(); try { // Call describeSObjects() passing in an array with one object type name DescribeSObjectResult[] dsrArray = binding.describeSObjects(new string[] { objectType }); // Since we described only one sObject, we should have only // one element in the DescribeSObjectResult array. DescribeSObjectResult dsr = dsrArray[0]; // First, get some object properties Console.WriteLine("\n\nObject Name: " + dsr.name); if (dsr.custom) Console.WriteLine("Custom Object"); if (dsr.label != null) Console.WriteLine("Label: " + dsr.label); // Get the permissions on the object if (dsr.createable) Console.WriteLine("Createable"); if (dsr.deletable) Console.WriteLine("Deleteable"); if (dsr.queryable) Console.WriteLine("Queryable"); if (dsr.replicateable) Console.WriteLine("Replicateable"); if (dsr.retrieveable) Console.WriteLine("Retrieveable"); if (dsr.searchable) Console.WriteLine("Searchable"); if (dsr.undeletable) Console.WriteLine("Undeleteable"); if (dsr.updateable) Console.WriteLine("Updateable"); Console.WriteLine("Number of fields: " + dsr.fields.Length); // Now, retrieve metadata for each field for (int i = 0; i < dsr.fields.Length; i++) { // Get the field Field field = dsr.fields[i]; // Write some field properties Console.WriteLine("Field name: " + field.name); Console.WriteLine("\tField Label: " + field.label); // This next property indicates that this // field is searched when using // the name search group in SOSL if (field.nameField) Console.WriteLine("\tThis is a name field."); if (field.restrictedPicklist) Console.WriteLine("This is a RESTRICTED picklist field."); Console.WriteLine("\tType is: " + field.type.ToString()); if (field.length > 0) Console.WriteLine("\tLength: " + field.length); if (field.scale > 0) Console.WriteLine("\tScale: " + field.scale); if (field.precision > 0) Console.WriteLine("\tPrecision: " + field.precision); if (field.digits > 0) Console.WriteLine("\tDigits: " + field.digits); if (field.custom) Console.WriteLine("\tThis is a custom field."); // Write the permissions of this field if (field.nillable) Console.WriteLine("\tCan be nulled."); if (field.createable) Console.WriteLine("\tCreateable"); if (field.filterable) Console.WriteLine("\tFilterable"); if (field.updateable) Console.WriteLine("\tUpdateable"); // If this is a picklist field, show the picklist values if (field.type.Equals(fieldType.picklist)) { Console.WriteLine("\tPicklist Values"); for (int j = 0; j < field.picklistValues.Length; j++) Console.WriteLine("\t\t" + field.picklistValues[j].value); } // If this is a foreign key field (reference), // show the values if (field.type.Equals(fieldType.reference)) { Console.WriteLine("\tCan reference these objects:"); for (int j = 0; j < field.referenceTo.Length; j++) Console.WriteLine("\t\t" + field.referenceTo[j]); } Console.WriteLine(""); } } catch (SoapException e) { Console.WriteLine("An exception has occurred: " + e.Message + "\nStack trace: " + e.StackTrace); } Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } private void querySample() { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; try { QueryResult qr = binding.query(soqlQuery); bool done = false; if (qr.size > 0) { Console.WriteLine("Logged-in user can see " + qr.records.Length + " contact records."); while (!done) { Console.WriteLine(""); sObject[] records = qr.records; for (int i = 0; i < records.Length; i++) { Contact con = (Contact)records[i]; string fName = con.FirstName; string lName = con.LastName; if (fName == null) Console.WriteLine("Contact " + (i + 1) + ": " + lName); else Console.WriteLine("Contact " + (i + 1) + ": " + fName + " " + lName); } if (qr.done) { done = true; } else { qr = binding.queryMore(qr.queryLocator); } } } else { Console.WriteLine("No records found."); } } catch (Exception ex) { Console.WriteLine("\nFailed to execute query succesfully," + "error message was: \n{0}", ex.Message); } Console.WriteLine("\nPress ENTER to continue..."); Console.ReadLine(); } } } ``` The following C# example is the same as the previous C# example, except it uses .NET 3.0 SoapClient services instead of .NET 2.0 SforceService services. ```class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ServiceModel; using Walkthrough.sforce; namespace Walkthrough { class QuickstartApiSample { private static SoapClient loginClient; // for login endpoint private static SoapClient client; // for API endpoint private static SessionHeader header; private static EndpointAddress endpoint; static void Main(string[] args) { QuickstartApiSample sample = new QuickstartApiSample(); sample.run(); } public void run() { // Make a login call if (login()) { // Do a describe global describeGlobalSample(); // Describe an account object describeSObjectsSample(); // Retrieve some data using a query querySample(); // Log out logout(); } } private bool login() { Console.Write("Enter username: "); string username = Console.ReadLine(); Console.Write("Enter password: "); string password = Console.ReadLine(); // Create a SoapClient specifically for logging in loginClient = new SoapClient(); // (combine pw and token if necessary) LoginResult lr; try { Console.WriteLine("\nLogging in...\n"); lr = loginClient.login(null, username, password); } catch (Exception e) { // Write the fault message to the console Console.WriteLine("An unexpected error has occurred: " + e.Message); // Write the stack trace to the console Console.WriteLine(e.StackTrace); return false; } // Check if the password has expired if (lr.passwordExpired) { Console.WriteLine("An error has occurred. Your password has expired."); return false; } /** Once the client application has logged in successfully, it will use * the results of the login call to reset the endpoint of the service * to the virtual server instance that is servicing your organization */ // On successful login, cache session info and API endpoint info endpoint = new EndpointAddress(lr.serverUrl); /** The sample client application now has a cached EndpointAddress * that is pointing to the correct endpoint. Next, the sample client * application sets a persistent SOAP header that contains the * valid sessionId for our login credentials. To do this, the sample * client application creates a new SessionHeader object. Add the session * ID returned from the login to the session header */ header = new SessionHeader(); header.sessionId = lr.sessionId; // Create and cache an API endpoint client client = new SoapClient("Soap", endpoint); printUserInfo(lr, lr.serverUrl); // Return true to indicate that we are logged in, pointed // at the right URL and have our security token in place. return true; } private void printUserInfo(LoginResult lr, String authEP) { try { GetUserInfoResult userInfo = lr.userInfo; Console.WriteLine("\nLogging in ...\n"); Console.WriteLine("UserID: " + userInfo.userId); Console.WriteLine("User Full Name: " + userInfo.userFullName); Console.WriteLine("User Email: " + userInfo.userEmail); Console.WriteLine(); Console.WriteLine("SessionID: " + lr.sessionId); Console.WriteLine("Auth End Point: " + authEP); Console.WriteLine("Service End Point: " + lr.serverUrl); Console.WriteLine(); } catch (Exception e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } } private void logout() { try { client.logout(header); Console.WriteLine("Logged out."); } catch (Exception e) { // Write the fault message to the console Console.WriteLine("An unexpected error has occurred: " + e.Message); // Write the stack trace to the console Console.WriteLine(e.StackTrace); } } /** * To determine the objects that are available to the logged-in * user, the sample client application executes a describeGlobal * call, which returns all of the objects that are visible to * the logged-in user. This call should not be made more than * once per session, as the data returned from the call likely * does not change frequently. The DescribeGlobalResult is * simply echoed to the console. */ private void describeGlobalSample() { try { // describeGlobal() returns an array of object results that // includes the object names that are available to the logged-in user. DescribeGlobalResult dgr = client.describeGlobal( header, // session header null // package version header ); Console.WriteLine("\nDescribe Global Results:\n"); // Loop through the array echoing the object names to the console for (int i = 0; i < dgr.sobjects.Length; i++) { Console.WriteLine(dgr.sobjects[i].name); } } catch (Exception e) { Console.WriteLine("An exception has occurred: " + e.Message + "\nStack trace: " + e.StackTrace); } } /** * The following method illustrates the type of metadata * information that can be obtained for each object available * to the user. The sample client application executes a * describeSObject call on a given object and then echoes * the returned metadata information to the console. Object * metadata information includes permissions, field types * and length and available values for picklist fields * and types for referenceTo fields. */ private void describeSObjectsSample() { Console.Write("\nType the name of the object to " + "describe (try Account): "); string objectType = Console.ReadLine(); try { // Call describeSObjects() passing in an array with one object type name DescribeSObjectResult[] dsrArray = client.describeSObjects( header, // session header null, // package version header null, // locale options new string[] { objectType } // object name array ); // Since we described only one sObject, we should have only // one element in the DescribeSObjectResult array. DescribeSObjectResult dsr = dsrArray[0]; // First, get some object properties Console.WriteLine("\n\nObject Name: " + dsr.name); if (dsr.custom) Console.WriteLine("Custom Object"); if (dsr.label != null) Console.WriteLine("Label: " + dsr.label); // Get the permissions on the object if (dsr.createable) Console.WriteLine("Createable"); if (dsr.deletable) Console.WriteLine("Deleteable"); if (dsr.queryable) Console.WriteLine("Queryable"); if (dsr.replicateable) Console.WriteLine("Replicateable"); if (dsr.retrieveable) Console.WriteLine("Retrieveable"); if (dsr.searchable) Console.WriteLine("Searchable"); if (dsr.undeletable) Console.WriteLine("Undeleteable"); if (dsr.updateable) Console.WriteLine("Updateable"); Console.WriteLine("Number of fields: " + dsr.fields.Length); // Now, retrieve metadata for each field for (int i = 0; i < dsr.fields.Length; i++) { // Get the field Field field = dsr.fields[i]; // Write some field properties Console.WriteLine("Field name: " + field.name); Console.WriteLine("\tField Label: " + field.label); // This next property indicates that this // field is searched when using // the name search group in SOSL if (field.nameField) Console.WriteLine("\tThis is a name field."); if (field.restrictedPicklist) Console.WriteLine("This is a RESTRICTED picklist field."); Console.WriteLine("\tType is: " + field.type.ToString()); if (field.length > 0) Console.WriteLine("\tLength: " + field.length); if (field.scale > 0) Console.WriteLine("\tScale: " + field.scale); if (field.precision > 0) Console.WriteLine("\tPrecision: " + field.precision); if (field.digits > 0) Console.WriteLine("\tDigits: " + field.digits); if (field.custom) Console.WriteLine("\tThis is a custom field."); // Write the permissions of this field if (field.nillable) Console.WriteLine("\tCan be nulled."); if (field.createable) Console.WriteLine("\tCreateable"); if (field.filterable) Console.WriteLine("\tFilterable"); if (field.updateable) Console.WriteLine("\tUpdateable"); // If this is a picklist field, show the picklist values if (field.type.Equals(fieldType.picklist)) { Console.WriteLine("\tPicklist Values"); for (int j = 0; j < field.picklistValues.Length; j++) Console.WriteLine("\t\t" + field.picklistValues[j].value); } // If this is a foreign key field (reference), // show the values if (field.type.Equals(fieldType.reference)) { Console.WriteLine("\tCan reference these objects:"); for (int j = 0; j < field.referenceTo.Length; j++) Console.WriteLine("\t\t" + field.referenceTo[j]); } Console.WriteLine(""); } } catch (Exception e) { Console.WriteLine("An exception has occurred: " + e.Message + "\nStack trace: " + e.StackTrace); } Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); } private void querySample() { String soqlQuery = "SELECT FirstName, LastName FROM Contact"; try { QueryResult qr = client.query( header, // session header null, // query options null, // mru options null, // package version header soqlQuery // query string ); bool done = false; if (qr.size > 0) { Console.WriteLine("Logged-in user can see " + qr.records.Length + " contact records."); while (!done) { Console.WriteLine(""); sObject[] records = qr.records; for (int i = 0; i < records.Length; i++) { Contact con = (Contact)records[i]; string fName = con.FirstName; string lName = con.LastName; if (fName == null) Console.WriteLine("Contact " + (i + 1) + ": " + lName); else Console.WriteLine("Contact " + (i + 1) + ": " + fName + " " + lName); } if (qr.done) { done = true; } else { qr = client.queryMore( header, // session header null, // query options qr.queryLocator // query locator ); } } } else { Console.WriteLine("No records found."); } } catch (Exception ex) { Console.WriteLine("\nFailed to execute query succesfully," + "error message was: \n{0}", ex.Message); } Console.WriteLine("\nPress ENTER to continue..."); Console.ReadLine(); } } } ``` # Step 4. Packaging Components for Customer Organizations To distribute the Apex triggers and the external client app to customers, partners can create a managed package. When customers install your managed package, they will be able to send push notifications to the external client app from their organizations when certain events occur on Salesforce records, such as updating records. Customers who install a managed package containing a external client app provided by a partner can't write their own Apex triggers to send push notifications to the external client app. This is to safeguard the partner's registration with the mobile OS vendor from abuse. # Step 5: Bulk Upsert This Bulk API 2.0 example guides you through creating a job, uploading data for the job, notifying Salesforce servers that your upload(s) are complete, checking the status, and retrieving the results. Some of the records exist (update), and some are new records (insert). 1. Confirm that your object is using an external ID field. Upserting records requires an external ID field on the object involved in the job. Bulk API 2.0 uses the external ID field to determine whether a record is used to update an existing record or create a record. This example assumes that the external ID field `customExtIdField__c` has been added to the `Account` object. To add this custom field in your org with Object Manager, use these properties. - Data Type—**text** - Field Label—**customExtIdField** - Select **External ID** For more information, see [Custom Fields](https://help.salesforce.com/s/articleView?id=platform.adding_fields.htm&type=5) in _Salesforce Help_. 2. Create a CSV file containing the records that you want to upsert. **note:** Save all files in this example in your terminal’s current working directory. The first row of the CSV file lists the field names for the object that you’re working with. Each subsequent row corresponds to a record that you want to insert. One column in the CSV file must correspond to the external ID field `customExtIdField__c`. For information on preparing CSV files, such as delimiter options and valid date and time formats, see [Bulk API 2.0 Ingest](https://developer.salesforce.com/docs/platform/api-asynch/bulk-api-2-0-ingest.md). For this example, copy this information into a file named `accountupsert.csv`. ```nolang customExtIdField__c,name,NumberOfEmployees 123,GenePoint,800 234,"United Oil & Gas, UK",1467 345,"United Oil & Gas, Singapore",348 456,Edge Communications,10045 567,Burlington Textiles Corp of America,5876 678,Dickenson plc,67 789,Grand Hotels & Resorts Ltd,409 890,Express Logistics and Transport,243 901,University of Arizona,9506 1350,United Oil & Gas Corp.,5467 1579,sForce,40000 2690,University of The Terrific,1257 ``` 3. Create a job that includes the external ID field. Copy this information into a file named `newupsertjob.json`. ```nolang { "object" : "Account", "externalIdFieldName" : "customExtIdField__c", "contentType" : "CSV", "operation" : "upsert", "lineEnding" : "LF" } ``` **URI** ```nolang /services/data/v68.0/jobs/ingest/ ``` **Example for creating a bulk upsert job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json" -H "X-PrettyPrint:1" -d @newupsertjob.json -X POST ``` **Example response body** The response includes the job ID, with a job state of Open. Use the job ID and the URL in the contentUrl field in the next step when you upload your data. ```nolang { "id" : "7476gEXAMPLE4X2ZWO", "operation" : "upsert", "object" : "Account", "createdById" : "0055fEXAMPLEtG4AAM", "createdDate" : "2022-01-02T21:57:03.000+0000", "systemModstamp" : "2022-01-02T21:57:03.000+0000", "state" : "Open", "externalIdFieldName" : "customExtIdField__c", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 68.0, "contentUrl" : "services/data/68.0/jobs/ingest/7476gEXAMPLE4X2ZWO/batches", "lineEnding" : "LF", "columnDelimiter" : "COMMA" } ``` 4. Upload the CSV data file that you created. **URI** For convenience, use the URI in the `contentUrl` field of the response from step 1. The URI is similar to: ```nolang /services/data/v68.0/jobs/ingest/jobId/batches/ ``` **Example for uploading data** ```nolang curl /services/data/v68.0/jobs/ingest/7476gEXAMPLE4X2ZWO/batches/ -H 'Authorization: Bearer ' -H "Content-Type: text/csv" --data-binary @accountupsert.csv -X PUT ``` **Example response body** No response body is returned. 5. Set `state` to `UploadComplete`. After you’re done submitting data, notify Salesforce servers that the upload of job data is complete and is ready for processing. Create a JSON file named upload_complete.json with the contents: ```nolang {"state":"UploadComplete"} ``` **URI** /services/data/v68.0/jobs/ingest/jobId/ **Example of setting `state` to `UploadComplete`** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/ingest/7476gEXAMPLE4X2ZWO/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json" -H "X-PrettyPrint:1" -d @upload_complete.json -X PATCH ``` **Example response body** ```nolang { "id" : "7476gEXAMPLE4X2ZWO", "operation" : "upsert", "object" : "Account", "createdById" : "", "createdDate" : "2022-01-02T21:28:22.000+0000", "systemModstamp" : "T21:28:22.000+0000", "state" : "UploadComplete", "externalIdFieldName" : "customExtIdField__c", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 68.0 } ``` 6. Get successful results. After a job is in the `JobComplete` or `Failed` state, you can get details about which job data records were successfully processed. **URI** ```nolang /services/data/v68.0/jobs/ingest/jobId/successfulResults/ ``` **Example of getting successful results** ```nolang curl /services/data/v68.0/jobs/ingest//successfulResults/ -H 'Authorization: Bearer ' -H "Content-Type: application/json" -H "Accept: text/csv" -H "X-PrettyPrint:1" -X GET ``` The response contains CSV formatted data, with each row containing a record ID of successfully processed records. **Example response body** ```nolang "sf__Id","sf__Created",customExtIdField__c,name,NumberOfEmployees "0018c00002DJIpJAAX","true","123","GenePoint","800" "0018c00002DJIpKAAX","true","234","United Oil & Gas, UK","1467" "0018c00002DJIpLAAX","true","345","United Oil & Gas, Singapore","348" "0018c00002DJIpMAAX","true","456","Edge Communications","10045" "0018c00002DJIpNAAX","true","567","Burlington Textiles Corp of America","5876" "0018c00002DJIpOAAX","true","678","Dickenson plc","67" "0018c00002DJIpPAAX","true","789","Grand Hotels & Resorts Ltd","409" "0018c00002DJIpQAAX","true","890","Express Logistics and Transport","243" "0018c00002DJIpRAAX","true","901","University of Arizona","9506" "0018c00002DJIpSAAX","true","1350","United Oil & Gas Corp.","5467" "0018c00002DJIpTAAX","true","1579","sForce","40000" "0018c00002DJIpUAAX","true","2690","University of The Terrific","1257" ``` To get details about records that encountered an error, use the `failedResults` resource. To make sure that you’re looking at the complete result set, use the `unprocessedRecords` resource. See [Get Job Unprocessed Record Results](https://developer.salesforce.com/docs/platform/api-asynch/reference/get-job-unprocessed-results.md). # Step 5: Test the PushTopic Channel 1. To load the Visualforce page in a web browser, click **Preview** on the Visualforce page editor: 2. In the text box, enter the channel name: /topic/InvoiceStatementUpdates. 3. To subscribe to the channel, click **Subscribe**. 4. Create or modify an invoice statement in a different browser tab. The page displays some debug messages and event notifications. The output resembles the following: ```nolang DEBUG: Handshake Successful: { "ext":{"replay":true,"payload.format":true}, "minimumVersion":"1.0", "clientId":"41kdiuvgig2tfxdh9weakuiwyh", "supportedConnectionTypes":["long-polling"], "channel":"/meta/handshake", "id":"1","version":"1.0","successful":true,"reestablish":false} DEBUG: Connection Successful : { "clientId":"41kdiuvgig2tfxdh9weakuiwyh", "advice":{ "interval":2000,"multiple-clients":true,"reconnect":"retry", "timeout":110000},"channel":"/meta/connect","id":"2", "successful":true} DEBUG: Subscribe Successful /topic/InvoiceStatementUpdates: {"clientId":"41kdiuvgig2tfxdh9weakuiwyh","channel":"/meta/subscribe", "id":"15","subscription":"/topic/InvoiceStatementUpdates","successful":true} { "event": { "createdDate": "2017-05-16T23:05:50.173Z", "replayId": 1, "type": "created" }, "sobject": { "Description__c": "New invoice.", "Id": "a00D0000009YbwQIAS", "Status__c": "Open", "Name": "INV-0001" } } _____________ { "event": { "createdDate": "2017-05-16T23:06:11.529Z", "replayId": 2, "type": "updated" }, "sobject": { "Description__c": "New invoice.", "Id": "a00D0000009YbwQIAS", "Status__c": "Negotiating", "Name": "INV-0001" } } _____________ ``` The debug messages contain information about the subscription status. The first event notification shows the notification data when an invoice statement is created. The second notification shows the notification data when an invoice statement is updated. Click **Unsubscribe** to unsubscribe from the channel and stop receiving notifications. # Step 6: Query Jobs This Bulk API 2.0 example shows you how to create a query job, monitor its progress, and get the job results. 1. Create the job. **URI** ```nolang /services/data/v68.0/jobs/query ``` **Example of creating a bulk query job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/query -H 'Content-Type: application/json' -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "X-PrettyPrint:1" --data-raw '{ "operation" : "query", "query" : "SELECT Id, Name FROM Account" } ' -X POST ``` The response includes the job `id` and shows the job’s state as `UploadComplete`. (You use the job `id` to monitor the job or get its results.) **Example response body** ```nolang { "id" : "7986gEXAMPLE4X2OPT", "operation" : "query", "object" : "Account", "createdById" : "0055fEXAMPLEtG4AAM", "createdDate" : "2022-01-02T17:38:59.000+0000", "systemModstamp" : "T17:38:59.000+0000", "state" : "UploadComplete", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 68.0, "lineEnding" : "LF", "columnDelimiter" : "COMMA" } ``` 2. Monitor the job’s state using the returned job `id`. **URI** ```nolang /services/data/v68.0/jobs/query/queryJobId ``` **Example of monitoring the state of the query job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/query/7986gEXAMPLE4X2OPT -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "X-PrettyPrint:1" -X GET ``` **Example response body** The response shows the current state of the job. Repeat this step until the state is `JobComplete`. ```nolang { "id" : "7986gEXAMPLE4X2OPT", "operation" : "query", "object" : "Account", "createdById" : "0055fEXAMPLEtG4AAM", "createdDate" : "2022-01-02T17:38:59.000+0000", "systemModstamp" : "T17:39:00.000+0000", "state" : "JobComplete", "concurrencyMode" : "Parallel", "contentType" : "CSV", "apiVersion" : 68.0, "jobType" : "V2Query", "lineEnding" : "LF", "columnDelimiter" : "COMMA", "numberRecordsProcessed" : 28, "retries" : 0, "totalProcessingTime" : 153, "isPkChunkingSupported": true } ``` 3. Get the results of the job. **URI** ```nolang /services/data/v68.0/jobs/query/queryJobId/results ``` **Example of getting the results of the job** ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/jobs/query/7986gEXAMPLE4X2OPT/results/ -H 'Authorization: Bearer 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE' -H "Content-Type: application/json; charset=UTF-8" -H "Accept: text/csv" -H "X-PrettyPrint:1" -X GET ``` The response shows the results of the SOQL query when you created the query job. **Example response body** ```nolang "Id","Name" "0015f00000BCvReAAL","Sample Account for Entitlements" "0015f00000BFjNuAAL","University of The Terrific" "0015f00000C6beUAAR","Edge Communications" "0015f00000C6beVAAR","Burlington Textiles Corp of America" "0015f00000C6beWAAR","Pyramid Construction Inc." "0015f00000C6beXAAR","Dickenson plc" "0015f00000C6beYAAR","Grand Hotels & Resorts Ltd" "0015f00000C6beZAAR","United Oil & Gas Corp." "0015f00000C6beaAAB","Express Logistics and Transport" "0015f00000C6bebAAB","University of Arizona" "0015f00000C6becAAB","United Oil & Gas, UK" "0015f00000C6bedAAB","United Oil & Gas, Singapore" "0015f00000C6beeAAB","GenePoint" ``` This example returns a small result set, and it’s easy to see the complete results. Queries that return larger results spread them across a sequence of result sets. To see the other result sets, use the locator to fetch the next set of results. For more information, see [Get Results for a Query Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/query-get-job-results.md). # Step Five: Abort a Job Abort an existing job by sending a POST request to this URI. The request URI identifies the job to abort. When a job is aborted, no more records are processed. If changes to data have been committed, they aren’t rolled back. **URI:** `/services/async/APIversion/job`/jobId **Example XML request body** ```xml Aborted ``` **Example XML response body** ```xml 750D0000000002lIAA insert Account 005D0000001ALVFIA4 2009-04-14T18:15:59.000Z 2009-04-14T18:16:00.000Z Aborted Parallel XML 0 0 1 0 1 2 0 36.0 0 3647 2136 0 ``` **Example JSON request body** ```nolang { "state" : "Aborted" } ``` **Example JSON response body** ```nolang { "apexProcessingTime" : 0, "apiActiveProcessingTime" : 2166, "apiVersion" : 36.0, "concurrencyMode" : "Parallel", "contentType" : "JSON", "createdById" : "005D0000001b0fFIAQ", "createdDate" : "2015-12-15T21:54:29.000+0000", "id" : "750D00000004SkVIAU", "numberBatchesCompleted" : 2, "numberBatchesFailed" : 0, "numberBatchesInProgress" : 0, "numberBatchesQueued" : 0, "numberBatchesTotal" : 2, "numberRecordsFailed" : 0, "numberRecordsProcessed" : 2, "numberRetries" : 0, "object" : "Account", "operation" : "insert", "state" : "Aborted", "systemModstamp" : "2015-12-15T21:54:29.000+0000", "totalProcessingTime" : 2870 } ``` **See Also** - [Step Four: Get Job Details](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-get-details.md) - [Step One: Create a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-create.md) - [Step Two: Monitor a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-monitor.md) - [Step Three: Close a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-close.md) - [Limits](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-concepts-limits.md) - [About URIs](https://developer.salesforce.com/docs/platform/api-asynch/basics/asynch-api-basics-about-uri.md) - [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md) # Step Five: Import the Data Now that all the pieces are in place, you can run Data Loader from the command line and insert some new accounts. **note:** The Data Loader command-line interface is supported for Windows only. |User Permissions Needed| | |-----------------------|--| |To insert records:|Create on the record| |To update records:|Edit on the record| |To upsert records:|Create or Edit on the record| |To delete records:|Delete on the record| |To hard delete records:|Delete on the record| 1. Copy the following data to a file named accountInsert.csv. It’s account data that you import into your organization. ```xml Name,Industry,NumberOfEmployees Dickenson plc,Consulting,120 GenePoint,Biotechnology,265 Express Logistics and Transport,Transportation,12300 Grand Hotels & Resorts Ltd,Hospitality,5600 ``` 2. In the command prompt window, enter the following command: `process.bat "<file path to process-conf.xml>" <process name>` - Replace \ with the path to the directory containing process-conf.xml. - Replace \ with the process specified in process-conf.xml. Your command looks something like this: `process.bat "C:\DLTest\Command Line\Config" accountInsert` After the process runs, the command prompt window displays success and error messages. You can also check the log files: insertAccounts_success.csv and insertAccounts_error.csv. After the process runs successfully, the insertAccounts_success.csv file contains the records that you imported, along with the ID and status of each record. For more information about the status files, see [Review Data Loader Output Files](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/reviewing-output-files.md). **See Also** - [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) # Step Four: Create the Configuration File The process-conf.xml file contains the information that Data Loader requires to process the data. Each `` in the process-conf.xml file refers to a single process such as an insert, upsert, or export. Therefore, this file can contain multiple processes. **note:** The Data Loader command-line interface is supported for Windows only. In this step, you edit the file to insert accounts into Salesforce. 1. Make a copy of the process-conf.xml file from the \samples\conf directory. Be sure to maintain a copy of the original because it contains examples of other types of Data Loader processing such as upserts and exports. 2. Open the file in a text editor, and replace the contents with the following XML. **note:** Remove `sfdc.password` if you're using OAuth for login authentication. ```xml accountInsert job gets the account record from the CSV file and inserts it into Salesforce. ``` 3. Modify the following parameters in the process-conf.xml file. For more information about the process configuration parameters, see [Data Loader Process Configuration Parameters](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/loader-params.md). - `sfdc.endpoint`—Enter the URL of the Salesforce instance for your organization; for example, https://_yourInstance_.salesforce.com/. - `sfdc.username`—Enter the username Data Loader uses to log in. - `sfdc.password`—Enter the encrypted password value that you created in step 2. - `process.mappingFile`—Enter the path and file name of the mapping file. - `dataAccess.Name`—Enter the path and file name of the data file that contains the accounts that you want to import. - `sfdc.debugMessages`—Currently set to `false`. Set it to `true` for troubleshooting. If set to `true`, debug messages are captured in the file specified by `sfdc.debugMessagesFile`. **note:** Debug messages can contain sensitive information such as session id. - `sfdc.debugMessagesFile`—Enter the path and file name of the command-line log file. - `process.outputSuccess`—Enter the path and file name of the success log file. - `process.outputError`—Enter the path and file name of the error log file. **note:** Use caution when using different XML editors to edit the process-conf.xml file. Some editors add XML tags to the beginning and end of the file, which causes the import to fail. 4. To perform operations in a sandbox org, set the following parameters. - `sfdc.oauth.environment`—Enter the value `Sandbox`. - `sfdc.endpoint.Sandbox`—Enter the value `test.salesforce.com`. **See Also** - [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) - [Step Five: Import the Data](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-import-data.md) # Step Four: Get Job Details Get all details for an existing job by sending a GET request to this URI. **URI:** `/services/async/APIversion/job`/jobId **Example request body** No request body is allowed. **Example XML response body** ```xml 750D00000004SkLIAU insert Account 005D0000001b0fFIAQ 2015-12-15T21:41:45.000Z 2015-12-15T21:41:45.000Z Open Parallel CSV 0 0 0 0 0 0 0 36.0 0 0 0 0 ``` **Example JSON response body** ```nolang { "apexProcessingTime" : 0, "apiActiveProcessingTime" : 0, "apiVersion" : 36.0, "concurrencyMode" : "Parallel", "contentType" : "JSON", "createdById" : "005D0000001b0fFIAQ", "createdDate" : "2015-12-15T20:45:25.000+0000", "id" : "750D00000004SkGIAU", "numberBatchesCompleted" : 0, "numberBatchesFailed" : 0, "numberBatchesInProgress" : 0, "numberBatchesQueued" : 0, "numberBatchesTotal" : 0, "numberRecordsFailed" : 0, "numberRecordsProcessed" : 0, "numberRetries" : 0, "object" : "Account", "operation" : "insert", "state" : "Open", "systemModstamp" : "2015-12-15T20:45:25.000+0000", "totalProcessingTime" : 0 } ``` **See Also** - [Step One: Create a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-create.md) - [Step Two: Monitor a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-monitor.md) - [Step Three: Close a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-close.md) - [Step Five: Abort a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-abort.md) - [Add a Batch to a Job](https://developer.salesforce.com/docs/platform/api-asynch/batches/asynch-api-batches-create.md) - [Limits](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-concepts-limits.md) - [About URIs](https://developer.salesforce.com/docs/platform/api-asynch/basics/asynch-api-basics-about-uri.md) - [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md) - [Quick Start: Bulk API 2.0](https://developer.salesforce.com/docs/platform/api-asynch/quickstart/asynch-api-quickstart.md) # Step One: Create a Job Create a job by sending a POST request to this URI. The request body identifies the type of object processed in all associated batches. **URI:** `/services/async/APIversion/job` **Example XML request body** ```xml insert Account CSV ``` **Example XML response body** ```xml 750D00000004SkLIAU insert Account 005D0000001b0fFIAQ 2015-12-15T21:41:45.000Z 2015-12-15T21:41:45.000Z Open Parallel CSV 0 0 0 0 0 0 0 36.0 0 0 0 0 ``` **Example JSON request body** ```nolang { "operation" : "insert", "object" : "Account", "contentType" : "JSON" } ``` **Example JSON response body** ```nolang { "apexProcessingTime" : 0, "apiActiveProcessingTime" : 0, "apiVersion" : 36.0, "concurrencyMode" : "Parallel", "contentType" : "JSON", "createdById" : "005D0000001b0fFIAQ", "createdDate" : "2015-12-15T20:45:25.000+0000", "id" : "750D00000004SkGIAU", "numberBatchesCompleted" : 0, "numberBatchesFailed" : 0, "numberBatchesInProgress" : 0, "numberBatchesQueued" : 0, "numberBatchesTotal" : 0, "numberRecordsFailed" : 0, "numberRecordsProcessed" : 0, "numberRetries" : 0, "object" : "Account", "operation" : "insert", "state" : "Open", "systemModstamp" : "2015-12-15T20:45:25.000+0000", "totalProcessingTime" : 0 } ``` In these samples, the `contentType` field indicates that the batches associated with the job are in CSV format. For alternative options, such as XML or JSON, see [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md). **warning:** The operation value must match that shown in [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md). For example, you get an error if you use INSERT instead of insert. **See Also** - [Create a Job for Batches with Binary Attachments](https://developer.salesforce.com/docs/platform/api-asynch/binary/binary-create-job.md) - [Step Four: Get Job Details](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-get-details.md) - [Step Three: Close a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-close.md) - [Step Five: Abort a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-abort.md) - [Add a Batch to a Job](https://developer.salesforce.com/docs/platform/api-asynch/batches/asynch-api-batches-create.md) - [Limits](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-concepts-limits.md) - [About URIs](https://developer.salesforce.com/docs/platform/api-asynch/basics/asynch-api-basics-about-uri.md) - [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md) - [Quick Start: Bulk API 2.0](https://developer.salesforce.com/docs/platform/api-asynch/quickstart/asynch-api-quickstart.md) # Step One: Create the Encryption Key File When you use Data Loader from the command line, there's no user interface. Therefore, you provide the information that you enter in the user interface in a text file named process-conf.xml. For example, you add the username and password that Data Loader uses to log in to Salesforce. **note:** The Data Loader command-line interface is supported for Windows only. **note:** The password must be encrypted before you add it to the process-conf.xml file, and creating the key is the first step in that process. 1. Open a command prompt window by selecting **Start** | **All Programs** | **Accessories** | **Command Prompt**. Alternatively, you can click **Start** | **Run**, enter `cmd` in the **Open** field, and click **OK**. 2. In the command window, enter `cd\` to navigate to the root directory of the drive where Data Loader is installed. 3. Navigate to the Data Loader \bin directory by entering this command. Replace the file path with the path from your system. C:\Users\{userName}\dataloader\version\bin 4. Create an encryption key file by entering the following command. Replace [_path to key file_] with the key file path. `encrypt.bat —k [path to key file]` For example: ```nolang C:\Users\jjang\Dataloader\v45\bin>encrypt.bat -k Keyfile "C:\Users\jjang\.dataloader\dataloader.key" was created! C:\Users\jjang\Dataloader\v45\bin> ``` **note:** To see a list of command-line options for encrypt.bat, enter `encrypt.bat` on the command line. 5. Note the key file path. In this example, the path is `C:\Users\{userName}\.dataloader\dataLoader.key`. The encryption utility encrypts passwords but not data. HTTPS with TLS 1.0 or later encrypts data transmitted by the Apex Data Loader. **See Also** - [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) - [Step Two: Create the Encrypted Password](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-create-enc-password.md) # Step One: Sign up for Salesforce Developer Edition Developer Edition provides a free and easy solution so that you can use Salesforce for testing and development. To sign up for a Developer Edition account, go to [developer.salesforce.com/signup](https://developer.salesforce.com/signup). **note:** The Developer Edition data storage maximum is 5 MB. This limit doesn’t prevent you from working with these examples. If you have a development sandbox, you can use it with these examples. Before you begin, verify that your user profile has the API Enabled permission by following the instructions in [User Permissions](https://help.salesforce.com/articleView?id=platform.admin_userperms.htm&type=5) in *Salesforce Help*. **See Also** - [*Salesforce Help*: User Permissions](https://help.salesforce.com/s/articleView?id=platform.admin_userperms.htm&type=5) - [*Knowledge Article*: Salesforce editions with API access](https://help.salesforce.com/articleView?id=000326486&type=1&mode=1) # Step Three: Close a Job Close a job by sending a POST request to this URI. The request URI identifies the job to close. When a job is closed, no more batches can be added. **URI:** `/services/async/APIversion/job`/jobId **Example XML request body** ```xml Closed ``` **Example XML response body** ```xml 750D0000000002lIAA insert Account 005D0000001ALVFIA4 2009-04-14T18:15:59.000Z 2009-04-14T18:15:59.000Z Closed Parallel XML 0 0 1 0 1 2 0 36.0 0 3647 2136 0 ``` **Example JSON request body** ```nolang { "state" : "Closed" } ``` **Example JSON response body** ```nolang { "apexProcessingTime" : 0, "apiActiveProcessingTime" : 5059, "apiVersion" : 36.0, "concurrencyMode" : "Parallel", "contentType" : "JSON", "createdById" : "005xx000001SyhGAAS", "createdDate" : "2015-11-19T01:45:03.000+0000", "id" : "750xx000000000GAAQ", "numberBatchesCompleted" : 10, "numberBatchesFailed" : 0, "numberBatchesInProgress" : 0, "numberBatchesQueued" : 0, "numberBatchesTotal" : 10, "numberRecordsFailed" : 0, "numberRecordsProcessed" : 100, "numberRetries" : 0, "object" : "Account", "operation" : "insert", "state" : "Closed", "systemModstamp" : "2015-11-19T01:45:03.000+0000", "totalProcessingTime" : 5759 } ``` **See Also** - [Step One: Create a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-create.md) - [Step Two: Monitor a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-monitor.md) - [Step Four: Get Job Details](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-get-details.md) - [Step Five: Abort a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-abort.md) - [Limits](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-concepts-limits.md) - [About URIs](https://developer.salesforce.com/docs/platform/api-asynch/basics/asynch-api-basics-about-uri.md) - [JobInfo](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-reference-jobinfo.md) - [Quick Start: Bulk API 2.0](https://developer.salesforce.com/docs/platform/api-asynch/quickstart/asynch-api-quickstart.md) # Step Three: Create the Field Mapping File In this step, you create a mapping file with an .sdl file extension. In each line of the mapping file, pair a data source with its destination. **note:** The Data Loader command-line interface is supported for Windows only. - Copy the following to a text file and save it with a name of accountInsertMap.sdl. This code is a data insert, so the data source is on the left of the equals sign and the destination field is on the right. ```xml #Mapping values #Thu May 26 16:19:33 GMT 2011 Name=Name NumberOfEmployees=NumberOfEmployees Industry=Industry ``` For complex mappings, you can use the Data Loader user interface to map source and destination fields and then save those mappings to an .sdl file. It’s done on the Mapping dialog box by clicking **Save Mapping**. **See Also** - [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) - [Step Four: Create the Configuration File](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-create-config-file.md) # Step Three: Walk Through the Sample Code To access different types of resources in Salesforce, make a series of REST requests. Before you try these examples, make sure to complete the prerequisites and obtain an access token in Step 1 of this Quick Start. You can copy and paste these examples to send them with cURL. But first replace MyDomainName in the base URI with your Salesforce domain. For information on the anatomy of a REST request, see [REST Resources and Requests](https://developer.salesforce.com/docs/platform/api-rest/intro/intro-rest-resources.md). ## Get the Salesforce Version To retrieve information about each available Salesforce version, submit a [Versions](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-versions.md) request. In this case, the request doesn’t require authentication. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/ ``` The output from this request, including the response header, specifies all valid versions. Your result can include more than one value. ```nolang Content-Length: 88 Content-Type: application/json; charset=UTF-8 Server: [ { "label":"Spring '11", "url":"/services/data/v21.0", "version":"21.0" } ... ] ``` ## Get a List of Resources To retrieve a list of the resources available for Salesforce, in this example, for version 68.0, submit a [Resources by Version](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-discoveryresource.md) request. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/ -H "Authorization: Bearer access_token" ``` The output from this request shows that `sobjects` is one of the available resources in Salesforce version 68.0. ```nolang { "sobjects" : "/services/data/v68.0/sobjects", "search" : "/services/data/v68.0/search", "query" : "/services/data/v68.0/query", "recent" : "/services/data/v68.0/recent" } ``` ## Get a List of Available Objects To request a list of the available objects, submit a [Describe Global](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-describeglobal.md) request. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/ -H "Authorization: Bearer access_token" ``` The output from this request shows that the Account object is available. ```nolang Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 Server: { "encoding" : "UTF-8", "maxBatchSize" : 200, "sobjects" : [ { "name" : "Account", "label" : "Account", "custom" : false, "keyPrefix" : "001", "updateable" : true, "searchable" : true, "labelPlural" : "Accounts", "layoutable" : true, "activateable" : false, "urls" : { "sobject" : "/services/data/v68.0/sobjects/Account", "describe" : "/services/data/v68.0/sobjects/Account/describe", "rowTemplate" : "/services/data/v68.0/sobjects/Account/{ID}" }, "createable" : true, "customSetting" : false, "deletable" : true, "deprecatedAndHidden" : false, "feedEnabled" : false, "mergeable" : true, "queryable" : true, "replicateable" : true, "retrieveable" : true, "undeletable" : true, "triggerable" : true }, }, ... ``` ## Get Basic Object Information To retrieve basic information about the available Account object’s metadata, submit a [sObject Basic Information](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-sobject-basic-info.md) request. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/ -H "Authorization: Bearer access_token" ``` The output from this request shows basic attributes of the Account object such as its name and label, and it lists the most recently used accounts. ```nolang { "objectDescribe" : { "name" : "Account", "updateable" : true, "label" : "Account", "keyPrefix" : "001", ... "replicateable" : true, "retrieveable" : true, "undeletable" : true, "triggerable" : true }, "recentItems" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000INjVeIAL" }, "Id" : "001D000000INjVeIAL", "Name" : "asdasdasd" }, ... ] } ``` ## Get a List of Fields To retrieve more detailed information, submit a [sObject Describe](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-sobject-describe.md) request. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/describe/ -H "Authorization: Bearer access_token" ``` The output from this request shows more detailed information about the Account object, such as its field attributes and child relationships. ```nolang { "name" : "Account", "fields" : [ { "length" : 18, "name" : "Id", "type" : "id", "defaultValue" : { "value" : null }, "updateable" : false, "label" : "Account ID", ... }, ... ], "updateable" : true, "label" : "Account", ... "urls" : { "uiEditTemplate" : "https://MyDomainName.my.salesforce.com/{ID}/e", "sobject" : "/services/data/v68.0/sobjects/Account", "uiDetailTemplate" : "https://MyDomainName.my.salesforce.com/{ID}", "describe" : "/services/data/v68.0/sobjects/Account/describe", "rowTemplate" : "/services/data/v68.0/sobjects/Account/{ID}", "uiNewRecord" : "https://MyDomainName.my.salesforce.com/001/e" }, "childRelationships" : [ { "field" : "ParentId", "deprecatedAndHidden" : false, ... }, ... ], "createable" : true, "customSetting" : false, ... } ``` ## Execute a SOQL Query To execute a SOQL query that retrieves a list of all the Account name values, submit a [Query](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-query.md) request. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/query?q=SELECT+name+from+Account -H "Authorization: Bearer access_token" ``` The output lists the available Account names, and each name’s preceding attributes include the Account IDs. ```nolang { "done" : true, "totalSize" : 14, "records" : [ { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IRFmaIAH" }, "Name" : "Test 1" }, { "attributes" : { "type" : "Account", "url" : "/services/data/v68.0/sobjects/Account/001D000000IomazIAB" }, "Name" : "Test 2" }, ... ] } ``` **note:** You can find more information about SOQL in the [Salesforce SOQL and SOSL Reference Guide](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/). ## Update a Field on a Record To retrieve one of the accounts and update its billing city, submit an [sObject Rows](https://developer.salesforce.com/docs/platform/api-rest/resources/resources-sobject-retrieve.md) request. To update the object, create a text file called patchaccount.json containing the new billing city information. ```nolang { "BillingCity" : "Fremont" } ``` Specify this JSON file in the REST request. The cURL notation requires the `—d` option when specifying data. For more information, see [http://curl.haxx.se/docs/manpage.html](http://curl.haxx.se/docs/manpage.html). Also, specify the `PATCH` method, which is used to update a REST resource. This cURL command retrieves the specified Account object using its ID field and updates its billing city. ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/sobjects/Account/001D000000IroHJ -H "Authorization: Bearer access_token" -H "Content-Type: application/json" --data-binary @patchaccount.json -X PATCH ``` No response body is returned, just the headers. ```nolang HTTP/1.1 204 No Content Server: Content-Length: 0 ``` To see that the billing address has changed to Fremont, refresh the page on the account. # Step Two: Create the Encrypted Password Create the encrypted password using the key file that you generated in the previous step. Skip this step if you're using OAuth for login authentication. **note:** The Data Loader command-line interface is supported for Windows only. 1. In the same command prompt window, enter the following command. `encrypt.bat -e ` Replace `` with the password that you use to log in to Salesforce in Data Loader combined with your org's [security token](https://help.salesforce.com/s/articleView?id=xcloud.user_security_token.htm&type=5) (no space in between). Replace `` with the file path you created in the previous step. For example, if your Data Loader password is `myP4sswordsRock` and your org's security token is `00DE0X0A0M0PeLE!AQcAQH0dMHEXAM`, then the command is: ```nolang encrypt.bat -e myP4sswordsRock00DE0X0A0M0PeLE!AQcAQH0dMHEXAM C:\Users\jjang\.dataloader\dataLoader.key ``` 2. Copy the generated encrypted password string. You use this value in a later step. **See Also** - [Data Loader Command Line Introduction](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-intro.md) - [Step Three: Create the Field Mapping File](https://developer.salesforce.com/docs/platform/data-loader-impl/guide/command-line-create-mapping-file.md) # Step Two: Monitor a Job You can monitor a Bulk API job in Salesforce. The monitoring page tracks jobs and batches created by any client application, including Data Loader or any client application that you write. To track the status of bulk data load jobs that are in progress or recently completed, enter `Bulk Data Load Jobs` in the Quick Find box, then select **Bulk Data Load Jobs**. This page allows you to monitor the progress of current jobs and the results of recent jobs. For more information, see [Manage Bulk Data Load Jobs](https://help.salesforce.com/s/articleView?id=xcloud.monitoring_async_api_jobs_overview.htm&type=5) in the Salesforce online help. **See Also** - [Step One: Create a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-create.md) - [Step Four: Get Job Details](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-get-details.md) - [Step Three: Close a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-close.md) - [Step Five: Abort a Job](https://developer.salesforce.com/docs/platform/api-asynch/guide/asynch-api-jobs-abort.md) - [Add a Batch to a Job](https://developer.salesforce.com/docs/platform/api-asynch/batches/asynch-api-batches-create.md) - [Limits](https://developer.salesforce.com/docs/platform/api-asynch/asynch-api-concepts-limits.md) # Step Two: Set Up Authentication To successfully send requests, REST API requires an access token obtained by authentication. Although you can create and authenticate against your own connected app, these Quick Start examples use Salesforce CLI for convenience. Salesforce CLI is a connected app that you can authenticate, and it requires no work to configure. Complete these steps in your [Developer Edition org or development sandbox](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_dev_org.htm). ## Get an Access Token with Salesforce CLI Use the access token (also known as a “bearer token”) that you get from Salesforce CLI to authenticate cURL requests. 1. Install or update Salesforce CLI. 1. If you already have Salesforce CLI installed, update it using the instructions in [Update Salesforce CLI](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_update_cli.htm). 2. If you need to [Install Salesforce CLI](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm), install the latest version for your operating system. 3. [Verify Your Installation](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm#sfdx_setup_install_cli_verify). 2. Log in to your Developer org with Salesforce CLI. ```nolang sf org login web ``` A browser opens to https://login.salesforce.com. To log in to a sandbox, append the `--instance-url` flag and specify your sandbox URL: ```nolang sf org login web --instance-url https://MyDomainName--SandboxName.sandbox.my.salesforce.com ``` 3. In the browser, log in to your Developer org or sandbox with your user’s credentials. 4. In the browser, click **Allow** to allow access. At the command line, you see a similar confirmation message. ```nolang Successfully authorized juliet.capulet@empathetic-wolf-g5qddtr.com with org ID 00D5fORGIDEXAMPLE ``` 5. At the command line, get the access token by viewing authentication information about your org. ```nolang sf org display --target-org ``` For example: ```nolang sf org display --target-org juliet.capulet@empathetic-wolf-g5qddtr.com ``` Example command output: ```nolang === Org Description KEY VALUE ─────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────── Access Token 00DE0X0A0M0PeLE!AQcAQH0dMHEXAMPLEzmpkb58urFRkgeBGsxL_QJWwYMfAbUeeG7c1EXAMPLEDUkWe6H34r1AAwOR8B8fLEz6nEXAMPLE Api Version 59.0 Client Id PlatformCLI Created By jules@sf.com Created Date 2023-11-16T20:35:21.000+0000 Dev Hub Id jules@sf.com Edition Developer Expiration Date 2023-11-23 Id 00D5fORGIDEXAMPLE Instance Url https://MyDomainName.my.salesforce.com Org Name Dreamhouse Signup Username juliet.capulet@empathetic-wolf-g5qddtr.com Status Active Username juliet.capulet@empathetic-wolf-g5qddtr.com ``` In the command output, make note of the long Access Token string and the Instance Url string. You need both to make cURL requests. **note:** To get a new token after your access token expires, repeat this step of viewing your authentication information. ## Optional Salesforce CLI Shortcuts After you’ve authenticated successfully, try out these optional shortcuts in your cURL workflow to streamline future authentication with the Salesforce CLI. **List My Orgs** ```nolang sf org list ``` Lists all the orgs that you’ve created or authenticated to. **Open My Org** ```nolang sf org open --target-org ``` Opens the specified org (identified by username or alias) in your browser. Because you’ve successfully authenticated with this org previously using the `org login web` Salesforce CLI command, it’s not required to provide your credentials again. **Display the Access Token for My Org** ```nolang sf org display --target-org ``` Output includes your access token, client ID, connected status, org ID, instance URL, username, and alias, if applicable. **Set an Alias for My Username** For convenience, create an alias for your username so that you don’t have to enter the entire Salesforce string. For example, instead of ```nolang juliet.capulet@empathetic-wolf-g5qddtr.com ``` Create an alias like ```nolang dev ``` To set the alias in this example, run ```nolang sf alias set dev juliet.capulet@empathetic-wolf-g5qddtr.com ``` **Use These Commands in a Script** Use the CLI’s JSON output by invoking the `--json` flag. Requesting JSON output provides a consistent output format, which is ideal for running scripts. Without the `--json` flag, the CLI can change the output format. **See Also** - [Salesforce CLI Setup Guide](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_intro.htm) - [Salesforce CLI Command Reference](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_unified.htm) - [_Salesforce Help_: Authorize Apps with OAuth](https://help.salesforce.com/articleView?id=xcloud.remoteaccess_authenticate.htm&type=5) # Steps for Implementing Mobile Notifications To implement mobile notifications, you configure each of the participating technologies. - **[Step 1. Developer Registration with Mobile OS Vendors](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-dev-registration.md)** This step asks the OS vendor to be prepared to handled Salesforce push notifications sent to your app. Developer registration also provides some information you’ll need to finish configuring your Salesforce external client app. - **[Step 2. Creating an External Client App](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-create-external-client-app-overview.md)** Once you’ve registered your mobile app with the OS vendor’s push service, the next step is to create an external client app in Salesforce. - **[Step 3. Configure Your Mobile SDK App](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-client-app.md)** In your Mobile SDK app, implement push notification protocols required by Salesforce and the device OS provider. - **[Step 4. Packaging Components for Customer Organizations](https://developer.salesforce.com/docs/platform/mobile-push-notifications/guide/pns-packaging.md)** To distribute the Apex triggers and the external client app to customers, partners can create a managed package. # stopPropagation() Sets whether the event can bubble or not. This method throws an error if called in the `"default"` phase. ## Signature `stopPropagation()` # Streaming API Calls Blocked by Security Settings Streaming API calls can be blocked if the session setting for locking sessions is enabled. Streaming API calls are blocked when both of these conditions apply. - The **Lock sessions to the IP address from which they originated** session setting is enabled in Setup. See [Modify Session Security Settings](https://help.salesforce.com/s/articleView?id=xcloud.admin_sessions.htm&type=5) in *Salesforce Help*. - The Streaming API client is using a session ID that was obtained from an IP address that’s different than the client’s IP address. To resolve this issue, make sure that the IP address from where the session originated matches the client’s IP address. Alternatively, disable the setting for locking sessions. # Streaming API 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_streaming.pdf) | | 67.0 | Summer '26 | [Download PDF](https://resources.docs.salesforce.com/262/latest/en-us/sfdc/pdf/api_streaming.pdf) | | 66.0 | Spring '26 | [Download PDF](https://resources.docs.salesforce.com/260/latest/en-us/sfdc/pdf/api_streaming.pdf) | | 65.0 | Winter '26 | [Download PDF](https://resources.docs.salesforce.com/258/latest/en-us/sfdc/pdf/api_streaming.pdf) | # Streaming API Error Codes Learn about the errors that Streaming API can return to troubleshoot your streaming client. |Error Code|Error Message|Error Description| |----------|-------------|-----------------| |400|API version in the URI is mandatory. URI format: '/cometd/68.0'|The API version information isn’t in the URI. Include the API version at the end of the URI. For example, `/cometd/`68.0.| |400|Unsupported API version. Only API versions '37.0' and later are supported. URI format: '/cometd/68.0'|The supplied API version in the URI is not supported. Only API version 37.0 and later are supported. The URI format is `/cometd/xx.x`.| |400|Invalid connection type {connection_type}|An invalid transport type was used. Only long-polling is supported, but another connection type was requested, such as WebSocket or callback long-polling.| |400|The channel you requested to subscribe to doesn’t exist {channel_name}|The streaming channel requested to subscribe to doesn’t exist. Ensure that the channel is created before subscribing.| |400|Channel name not specified|The channel name wasn’t specified. Specify a valid channel name to subscribe to.| |400|Channel subscriptions must start with a leading '/'|The channel name format is invalid. Channel names must start with a leading slash (/).| |400|Query fields {query_fields} do not exist on the topic entity|The supplied query fields don’t exist on the Salesforce object specified in the PushTopic.| |400|Client client_name has established a session, but no cookie_name cookie present|No cookie was found after the client established a session. Ensure that the streaming client accepts cookies.| |400|The replayId {replay_id} you provided was invalid. Please provide a valid ID, -2 to replay all events, or -1 to replay only new events.|The supplied replay ID is invalid. Ensure that the replay ID corresponds to an event that is within the retention window and that has not been deleted. Alternatively, provide -2 to replay all events or -1 to replay only new events.| |400|Authenticated user id does not match the session's user id|The CometD session in the browser is associated with more than on user. This error can occur if you're using the [Lightning Emp API](https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api) component and logged in as another user using system admin login as feature. See [Log In as Another User](https://help.salesforce.com/s/articleView?id=xcloud.logging_in_as_another_user.htm&type=5) in *Salesforce Help*. For more details, see [this knowledge article](https://help.salesforce.com/s/articleView?id=004633785&type=1).| |401|Authentication invalid.|The supplied authentication token or session ID is not valid. This error is returned on the `/meta/handshake` or the `/meta/connect` channel. On the `/meta/handshake` channel, the error is in the `failureReason` response field, which is nested under the `ext/sfdc` field. On the `/meta/connect` channel, the error is in the `error` field.| |401|Request requires authentication.|No authentication token or session ID was supplied in the request header. The client must send authentication information. This error is returned in the handshake error response (on the `/meta/handshake` channel) in the `failureReason` response field, which is nested under the `ext/sfdc` field. The `error` field in the response also contains the following error: `403::Handshake denied`.| |403|Cannot create channel {channel_name}|The subscription channel can’t be created, which can be due to insufficient permissions.| |403|Subscriber does not have access to the entity in this topic|The subscriber doesn’t have access to the Salesforce object in the PushTopic.| |403|Subscriber does not have access to all fields referenced in the where clause of the PushTopic|The subscriber doesn’t have access to all fields referenced in the WHERE clause of the PushTopic.| |403|Handshake denied|The handshake request was denied. The cause of this error is provided in the `failureReason` field in the response, which is nested under the `ext/sfdc` field.| |403|Client has not completed handshake|The client has not completed a handshake. The client must perform a handshake before subscribing.| |403|Organization concurrent user limit exceeded|The maximum number of concurrent clients across all channels has been exceeded. This error applies to any type of event, including PushTopic, generic, platform, and Change Data Capture events.| |403|Organization total events daily limit exceeded|The maximum number of delivered event notifications within a 24-hour period to all CometD clients has been exceeded. This error applies to any type of event, including PushTopic, generic, platform, and Change Data Capture events.| |403|Restricted channel|The user doesn’t have the required permissions to subscribe to the streaming channel.| |403|User not enabled for streaming|The user doesn’t have read permission on the PushTopic.| |403|User not allowed to subscribe CDC without View All Data permissions|The user must have the View All Data permission to subscribe to Change Data Capture.| |403|Subscription limit exceeded for this topic|The maximum number of concurrent clients per topic for PushTopic and generic events has been exceeded. This error doesn’t apply to platform events.| |403|Unknown client|The server deleted the client CometD session due to a timeout, which can be caused by a network failure or by Hyperforce’s auto-scaling processes as part of elastic computing. The client must perform a new handshake and reconnect.| |403|To protect all customers from excessive use and Denial of Service attacks, we limit the number of simultaneous connections per server. Your request has been denied because this limit has been exceeded. Please try your request again later.|Salesforce app servers enforce a limit on simultaneous connections per server to protect from excessive use and denial of service attacks. Your request has been denied because this limit has been exceeded. Try your request again later. This error is returned in a handshake response (on the `/meta/handshake` channel) in the `failureReason` response field, which is nested under the `ext/sfdc` field. The response also contains an error in the `error` field: `403::Handshake denied`.| |413|Maximum Request Size Exceeded|The maximum request size of 32,768 bytes has been exceeded.| |503|Server is too busy. Please try your request again later.|The server can’t process your request because it is too busy. Try your request again later, or try to execute your requests serially. This error is returned in the `failureReason` response field, which is nested in the `ext/sfdc` field on channels, such as the `/meta/handshake`, `/meta/connect`, or `/meta/subscribe` channels. The `error` field in the response contains another error alongside this error.| ## Generic Streaming-only Errors The following errors are returned for generic streaming events only. |Error Code|Error Message|Error Description| |----------|-------------|-----------------| |403|Unable to create channel dynamically, maximum channel limit has been exceeded|The maximum number of generic streaming channels has been exceeded.| |403|No access on channel|The generic streaming channel can’t be accessed because the user doesn’t have permissions on the StreamingChannel object.| |404|channel names may not vary only by case|The generic streaming channel exists with a different case. Generic streaming channel names are case-sensitive.| |404|Unknown channel|The generic streaming channel isn’t found or can’t be created dynamically.| # Streaming API Notifications Sent in Reverse Order Within a Transaction In general, event notifications are delivered in the order of record changes. One exception is that when a record triggers multiple notifications within the same transaction, the last notifications are delivered first. For example, let’s say you have a PushTopic for insertions and updates of contact records, and the PushTopic query selects `fieldA`. If a contact is inserted and then an Apex trigger or workflow updates `fieldA` in the same transaction, the order of notifications sent is: - Notification for the update of `fieldA` - Notification for the insertion of the record In this case, the order of notifications depends on the order in which the Lightning Platform commits transactions. # Streaming API Terms Learn about terms used for Streaming API. |Term|Description| |----|-----------| |Event|The creation, update, delete, or undelete of a record. Each event might trigger a notification.| |Notification|A message in response to an event. The notification is sent to a channel to which one or more clients are subscribed.| |PushTopic|A PushTopic triggers notifications for changes in Salesforce records resulting from a create, update, delete, or undelete operation. A PushTopic notification is based on the criteria that you specify in the PushTopic record and the SOQL query that you define. Only the fields specified in the query are included in the notification. The PushTopic defines a subscription channel.| |Channel|A stream of events to which a client can subscribe to receive event notifications.| |Event Bus|A conduit in which a publisher sends an event notification. Event subscribers subscribe to a channel in the event bus to receive event notifications. The event bus supports replaying stored event messages.| |Platform Event|A Salesforce entity that represents the definition of the custom data that you send in a platform event message. You create a platform event and define its fields in Salesforce. The subscription channel is based on the platform event name.| |Change Data Capture Event|Similar to a PushTopic, Change Data Capture triggers notifications for changes in Salesforce records resulting from a create, update, delete, or undelete operation. Unlike a PushTopic, Change Data Capture sends all changed fields of a record and doesn’t require you to specify the fields in a query. Also, Change Data Capture sends information about the change in headers.| # Streaming API vs. Pub/Sub API Pub/Sub API is a newer API that you can use to publish and subscribe to platform events and change data capture events. Based on gRPC API and HTTP/2, Pub/Sub API efficiently publishes and delivers binary event messages, and supports multiple programming languages. Before Pub/Sub API was introduced, the only way to subscribe to events in an external client was with Streaming API. This table compares some features of the two subscription APIs. | |Streaming API|Pub/Sub API| |--|-------------|-----------| |Event encoding|JSON|Binary ([Apache Avro](https://avro.apache.org/))| |Protocol|[CometD](https://cometd.org/), an implementation of the Bayeux protocol.|[gRPC](https://grpc.io/docs/what-is-grpc/) and protocol buffers| |Subscription model|Push-based—The server delivers events as they become available in the event bus.|Pull-based—The client requests the number of events to receive as they become available in the event bus.| |Subscription flow control|The client doesn’t control the number of events delivered from the server.|The client specifies how many events to receive for a Subscribe call based on event processing speed.| |Publish status|Not supported with Streaming API. When using data APIs to publish events, the event queueing result is returned. When system resources are available, queued events are published. The final result isn’t returned to the client.|The final publishing result returned indicates that the event was successfully published or that the publish failed.| **See Also** - [*Pub/Sub API Developer Guide*](https://developer.salesforce.com/docs/platform/pub-sub-api/overview) # Streaming Event Features The Lightning Platform offers several types of streaming events. To determine which event meets your use case, compare the features of the various events. **important:** PushTopic and generic events are legacy products. Salesforce no longer enhances them with new features and provides limited support for them. Instead of PushTopic events, consider using Change Data Capture events. Instead of generic events, consider using Platform Events. To learn about Change Data Capture events, see the [Change Data Capture Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm) and the [Change Data Capture Basics](https://trailhead.salesforce.com/content/learn/modules/change-data-capture) Trailhead module. To learn about Platform Events, see [Platform Events Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_intro.htm) and the [Platform Events Basics Trailhead module](https://trailhead.salesforce.com/content/learn/modules/platform_events_basics). |Feature|Change Data Capture Event|Platform Event|PushTopic Event (Legacy)|Generic Event (Legacy)| |:------|:-----------------------:|:------------:|------------------------|:--------------------:| |Define a custom schema as strongly typed fields|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Include user-defined payloads|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)| |Publish custom events via one or more APIs|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)| |Publish events via Apex|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Publish declaratively using Process Builder and Flow Builder|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Publish to specific users|N/A|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)| |Subscribe via CometD using JavaScript, Java, and other languages|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)| |Subscribe via Pub/Sub API|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Subscribe via Apex triggers|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Filter subscriptions|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Receive auto-published event notifications for Salesforce record changes|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A| |Choose the fields to include in event notifications for Salesforce record changes|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A| |Receive a versioned event schema|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Get field-level security|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Get record-sharing support|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|N/A|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|N/A| |Encrypt field data with Shield Platform Encryption|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)|![No](https://developer.salesforce.com/media/api-streaming/x_16.png)| |Replay retained event notifications|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)|![Yes](https://developer.salesforce.com/media/api-streaming/checkmark_16.png)| |Event retention period|3 days|3 days:sup[\*]|1 day|1 day| :sup[\*] Standard-volume platform events are retained for 1 day. **See Also** - [*Platform Events Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_intro_emp.htm) - [*Change Data Capture Developer Guide*](https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm) # Style Existing Visualforce Pages with Lightning Experience Stylesheets You can control whether a page is styled with the look of Lightning Experience when viewed in Lightning Experience or the Salesforce mobile app with the `lightningStylesheets` attribute. **note:** The `lightningStylesheets` attribute isn’t supported in Experience Cloud sites. To style your Visualforce page to match the Lightning Experience UI when viewed in Lightning Experience or the Salesforce mobile app, set `lightningStylesheets="true"` in the `` tag. When the page is viewed in Salesforce Classic, it doesn’t get Lightning Experience styling. ```visualforce ``` If `lightningStylesheets="true"`, the CSS scoping class `slds-vf-scope` is automatically applied to the Visualforce page’s `` element. The scoping class is applied so that your content matches the Lightning Experience UI. If you set `applyBodyTag` or `applyHtmlTag` to false, you must manually add the scoping class `slds-vf-scope`. Here is a standard Visualforce page without the `lightningStylesheets` attribute. The page is styled with the Classic UI.![Visualforce page not styled with the lightningStylesheets attribute. It is styled with the Classic UI.](https://developer.salesforce.com/media/salesforce-pages-developers-guide/vf_lightning_stylesheets_classic.png) Here is the same Visualforce page with the `lightningStylesheets` attribute set to `true`.![Visualforce page with the lightningStylesheets attribute set to true. The UI matches Lightning Experience.](https://developer.salesforce.com/media/salesforce-pages-developers-guide/vf_lightning_stylesheets_true.png) You can style most commonly used Visualforce components with the `lightningStylesheets` attribute. However, some components differ slightly in style from Lightning Experience. For example, ``, and some `` elements use the browser’s default styling instead. Commonly used Visualforce components that don’t require styling, such as ``, ``, and ``, are still supported. To include custom SLDS components that aren’t part of the Visualforce component library, use the `` tag with the code and the `lightningStylesheets` attribute. **note:** - The`lightningStylesheets` attribute doesn’t affect custom styling. Custom code must be updated to match the page’s SLDS styling. - If set to false, the `standardStylesheets` attribute for `` overrides and suppresses `lightningStylesheets` in Lightning Experience, Salesforce Classic, and the mobile app. - The `` component has known issues when creating PDF files from Visualforce pages. For this reason, `lightningStyleSheets` does not support `` or calls to `PageReference.getContentAsPDF().` When using `lightningStylesheets="true"`, most Visualforce buttons display as the neutral variant. Neutral styling of buttons occurs because there’s no selector hook to reliably determine which buttons must be branded. Add the `.slds-vf-button_brand` style attribute to the `` to create a button styled based on your org branding: ```visualforce ``` **note:** When building new features, use `` and implement the button using the Lightning Design System Button blueprint. The following Visualforce components support the `lightningStylesheets` attribute or don’t require styling. - `analytics:reportChart` - `apex:actionFunction` - `apex:actionPoller` - `apex:actionRegion` - `apex:actionStatus` - `apex:actionSupport` - `apex:areaSeries` - `apex:attribute` - `apex:axis` - `apex:barSeries` - `apex:canvasApp` - `apex:chart` - `apex:chartLabel` - `apex:chartTips` - `apex:column` - `apex:commandButton` - `apex:commandLink` - `apex:component` - `apex:componentBody` - `apex:composition` - `apex:dataList` - `apex:dataTable` - `apex:define` - `apex:detail` - `apex:dynamicComponent` - `apex:enhancedList` - `apex:facet` - `apex:flash` - `apex:form` - `apex:gaugeSeries` - `apex:iframe` - `apex:image` - `apex:include` - `apex:includeLightning` - `apex:includeScript` - `apex:inlineEditSupport` - `apex:input` - `apex:inputCheckbox` - `apex:inputField` - `apex:inputFile` - `apex:inputHidden` - `apex:inputSecret` - `apex:inputText` - `apex:inputTextArea` - `apex:insert` - `apex:legend` - `apex:lineSeries` - `apex:listViews` - `apex:map` - `apex:mapMarker` - `apex:message` - `apex:messages` - `apex:outputField` - `apex:outputLabel` - `apex:outputLink` - `apex:outputPanel` - `apex:outputText` - `apex:page` - `apex:pageBlock` - `apex:pageBlockButtons` - `apex:pageBlockSection` - `apex:pageBlockSectionItem` - `apex:pageBlockTable` - `apex:pageMessage` - `apex:pageMessages` - `apex:panelBar` - `apex:panelBarItem` - `apex:panelGrid` - `apex:panelGroup` - `apex:param` - `apex:pieSeries` - `apex:radarSeries` - `apex:relatedList` - `apex:remoteObjectField` - `apex:remoteObjectModel` - `apex:remoteObjects` - `apex:repeat` - `apex:scatterSeries` - `apex:scontrol` - `apex:sectionHeader` - `apex:selectCheckboxes` - `apex:selectList` - `apex:selectOption` - `apex:selectOptions` - `apex:selectRadio` - `apex:stylesheet` - `apex:tab` - `apex:tabPanel` - `apex:toolbar` - `apex:toolbarGroup` - `apex:variable` - `chatter:feed` - `chatter:feedWithFollowers` - `chatter:follow` - `chatter:newsFeed` - `flow:interview` - `site:googleAnalyticsTracking` - `site:previewAsAdmin` - `topics:widget` # Styling Apps An app is a special top-level component whose markup is in a `.app` resource. Just like any other component, you can put CSS in its bundle in a resource called `.css`. For example, if the app markup is in `notes.app`, its CSS is in `notes.css`. When viewed in Salesforce for Android, iOS, and Lightning Experience, the components include styling that matches those visual themes. For example, the `lightning:button` includes the `slds-button_neutral` class to display a neutral style. **note:** Styles added to Lightning components in Salesforce for Android, iOS, and Lightning Experience don’t apply to components in standalone apps. - **[Using the Salesforce Lightning Design System in Apps](https://developer.salesforce.com/docs/platform/aura-platform/guide/apps-slds.md)** The Salesforce Lightning Design System (SLDS) provides a look and feel that’s consistent with Lightning Experience. Use Lightning Design System styles to give your custom stand-alone Lightning applications a UI that is consistent with Salesforce, without having to reverse-engineer our styles. - **[Using External CSS](https://developer.salesforce.com/docs/platform/aura-platform/guide/apps-css-external-platform.md)** To reference an external CSS resource, upload it as a static resource and use a `` tag in your `.cmp` or `.app` markup. - **[More Readable Styling Markup with the join Expression](https://developer.salesforce.com/docs/platform/aura-platform/guide/apps-css-markup.md)** Markup can get messy when you specify the class names to apply based on the component attribute values. Try using a `join` expression for easier-to-read markup. - **[Tips for CSS in Components](https://developer.salesforce.com/docs/platform/aura-platform/components/components-css-tips.md)** Here are some tips for configuring the CSS for components that you plan to use in Lightning pages, the Lightning App Builder, or the Experience Builder. - **[CSS for RTL Languages](https://developer.salesforce.com/docs/platform/aura-platform/guide/apps-css-rtl.md)** When your Language setting in Salesforce is set to a right-to-left (RTL) language, the framework automatically flips property names, such as `left` and `border-left` to `right` and `border-right` respectively. The framework also rearranges certain values like `padding`, `margin`, and `border-radius` so that the `right` and `left` units are swapped. - **[Styling with Design Tokens and Styling Hooks](https://developer.salesforce.com/docs/platform/aura-platform/tokens/tokens-intro.md)** Capture the essential values of your visual design into named tokens or global styling hooks. Reuse these values throughout your Lightning components CSS resources. Tokens and styling hooks make it easy to ensure that your design is consistent, and even easier to update your design as it evolves. **See Also** - [CSS in Components](https://developer.salesforce.com/docs/platform/aura-platform/components/components-css.md) # Styling Pages that Use Standard Controllers Any page associated with a standard controller automatically inherits the style that is used for standard Salesforce pages associated with the specified object. That is, the tab for the specified object appears selected, and the associated color of the tab is used to style all page elements. You can override the styling of a page that uses a standard controller with the `tabStyle` attribute on the `` tag. For example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses the Opportunity tab's yellow coloring: ```markup ``` To use the styling associated with MyCustomObject: ```markup ``` To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use: ```markup ``` Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles. **See Also** - [Styling Visualforce Pages](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/styling/pages-styling.md) # Styling Visualforce Pages It’s easy to style a Visualforce page, either by mimicking the look and feel of a standard Salesforce page, or by using your own stylesheets or content types. Many Visualforce components have a `style` or `styleClass` attribute. Defining either of these attributes allows you to associate CSS code with the component. Custom CSS code enables you to change the default visual style of a component, including its width, height, color, and font. - **[Using Salesforce Styles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-salesforce.md)** Many Visualforce components already have the look and feel of the same components in Salesforce, such as the related list in a detail page, or a section header. Part of the styling of these components, including the component’s color scheme, is based on the tab on which the component appears. You can specify the tab style that should be used to style a component by associating a page with a standard controller, or by setting the `tabStyle` attribute on the `` or `` tags. - **[Extending Salesforce Styles with Stylesheets](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-adding-stylesheets.md)** Use the `` tag to add additional stylesheets to a page. Use the `style` or `styleClass` attribute available on most Visualforce components to connect them to style definitions in your stylesheets. This technique lets you extend the Salesforce styles with your own. - **[Using the Lightning Design System](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-slds.md)** Use the `` element to incorporate the Lightning Design System in your Visualforce pages and align them with the styling of Lightning Experience. This component is a streamlined alternative to uploading the Lightning Design System as a static resource and using it in your Visualforce pages. - **[Style Existing Visualforce Pages with Lightning Experience Stylesheets](https://developer.salesforce.com/docs/platform/salesforce1/developer/dev-best-practices/vf-dev-best-practices-slds-lightningstylesheets.md)** You can control whether a page is styled with the look of Lightning Experience when viewed in Lightning Experience or the Salesforce mobile app with the `lightningStylesheets` attribute. - **[Using Custom Styles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-custom.md)** Use the `` tag or static HTML to include your own style sheet or styles. - **[Suppressing the Salesforce User Interface and Styles](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-suppressing-salesforce-stylesheets.md)** By default, Visualforce pages adopt the same visual styling and user interface “chrome” as the rest of Salesforce. This default styling behavior lets you create pages that look like they’re built right into Salesforce. If you don’t want a page to have the Salesforce look and feel, you can suppress various aspects of the Salesforce page and visual design. - **[Defining Styles for a Component’s DOM ID](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-custom-using-component-id.md)** Use CSS attribute selectors for the style definition if you want to apply a style using a DOM ID. Attribute selectors rely on the definition of an attribute, rather than an HTML tag, to apply a CSS style. - **[Using Styles from Salesforce Stylesheets](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-using-salesforce-stylesheets.md)** Salesforce uses different stylesheets (.css files) throughout the application to ensure that every tab conforms to the Salesforce look and feel. These stylesheets are automatically included on a Visualforce page unless you specify `false` for the `showHeader` attribute of the `` tag. - **[Identifying the Salesforce Style Your Users See](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-salesforce-identifying-theme.md)** When you’re creating a Visualforce page, it’s often useful to know the Salesforce look and feel your user expects, in order to render a page that matches their style. For example, some users have the choice to customize their look and feel. You’ll need to design your Visualforce pages to take these differences into consideration. - **[Determining the Salesforce Style That Users See in JavaScript](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-styling-javascript-identifying-theme.md)** If you use a lot of JavaScript in your pages and apps, identifying the Salesforce theme that a user sees in JavaScript code is important. Identifying the current user experience context allows you to correctly manage navigation in your JavaScript code. # Styling with Design Tokens and Styling Hooks Capture the essential values of your visual design into named tokens or global styling hooks. Reuse these values throughout your Lightning components CSS resources. Tokens and styling hooks make it easy to ensure that your design is consistent, and even easier to update your design as it evolves. **important:** Salesforce recommends that you use [Styling Hooks](https://www.lightningdesignsystem.com/platforms/lightning/styling-hooks/) instead of design tokens if possible. While existing design tokens still work, styling hooks are the future of customization for Lightning web components and Aura components. See [Replace Design Tokens with Styling Hooks](https://developer.salesforce.com/docs/platform/aura-platform/guide/styling-hooks.md). Design tokens and styling hooks are visual design “atoms” for building a design for your components or apps. Specifically, they’re named entities that store visual design attributes: pixel values for margins and spacing, font sizes and families, or hex values for colors. Both design tokens and styling hooks are a terrific way to centralize the low-level values, which you then use to compose the styles that make up the design of your component or app. - **[Tokens Bundles](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-bundles.md)** Tokens are a type of bundle, just like components, events, and interfaces. - **[Create a Tokens Bundle](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-create-bundle.md)** Create a tokens bundle in your org using the Developer Console. - **[Defining and Using Tokens](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-using.md)** A token is a name-value pair that you specify using the `` component. Define tokens in a tokens bundle, and then use tokens in your components’ CSS styles resources. - **[Using Expressions in Tokens](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-expressions.md)** Tokens support a restricted set of expressions. Use expressions to reuse one token value in another token, or to combine tokens to form a more complex style property. - **[Extending Tokens Bundles](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-extending.md)** Use the `extends` attribute to extend one tokens bundle from another. - **[Using Standard Design Tokens](https://developer.salesforce.com/docs/platform/aura-platform/guide/tokens-standard.md)** Salesforce exposes a set of “base” tokens that you can access in your component style resources. Use these standard tokens to mimic the look-and-feel of the Salesforce Lightning Design System (SLDS) in your own custom components. - **[Replace Design Tokens with Styling Hooks](https://developer.salesforce.com/docs/platform/aura-platform/guide/styling-hooks.md)** If you use design tokens to customize the styling of your Aura components, use SLDS global styling hooks instead. Custom components that use design tokens still work, but they no longer receive updates after LWC API version 61.0. By using styling hooks, you can cleanly adopt future product innovations and updated web accessibility standards. # Submit a Record for Approval Use the Process Approvals resource to submit a record or a collection of records for approval. Each call takes an array of requests. ## Example usage ```nolang curl https://MyDomainName.my.salesforce.com/services/data/v68.0/process/approvals/ -H "Authorization: Bearer token" -H "Content-Type: application/json" -d @submit.json" ``` ## Example request body submit.json file In the following example, the record "001D000000I8mIm" is submitted for approval process "PTO_Request_Process" by skipping its entry criteria on behalf of submitter "005D00000015rZy." ```nolang { "requests" : [{ "actionType": "Submit", "contextId": "001D000000I8mIm", "nextApproverIds": ["005D00000015rY9"], "comments":"this is a test", "contextActorId": "005D00000015rZy", "processDefinitionNameOrId" : "PTO_Request_Process", "skipEntryCriteria": "true"}] } ``` ## Example JSON response body ```nolang [ { "actorIds" : [ "005D00000015rY9IAI" ], "entityId" : "001D000000I8mImIAJ", "errors" : null, "instanceId" : "04gD0000000Cvm5IAC", "instanceStatus" : "Pending", "newWorkitemIds" : [ "04iD0000000Cw6SIAS" ], "success" : true } ] ``` # Submit Exchange Order Submits an exchange order based on the specified information. To access, you need the following permissions: Salesforce Order Management License or Salesforce B2B Commerce License. This object is available in API version 60.0 and later. ## Supported REST HTTP Methods **URI:** `/services/data/v59.0/actions/standard/previewCartToExchangeOrder` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`exchangeCartId`|ID|Required. The ID of the cart record containing the items in the exchange order.| |`orderNumber`|ID|Optional. Order number for the created exchange order summary.| |`orderSummaryId`|ID|Required. The ID of the order summary record associated with the list of exchanges.| |`paymentInfoInputs`|Collection|Optional. A collection of Apex ConnectApi.PaymentInfoInputRepresentation records, each containing payment details when the exchange order amount is greater than the original order amount.| |`referenceId`|ID|Required. The ID of the record that's related to the specified order summary. Only IDs from a return order record are supported.| |`sequenceList`|Collection|Optional. A collection of Apex ConnectApi.SequenceOrderPaymentSummaryInputRepresentation records to reserve a balance from. Each record contains an order summary payment ID and an amount.| ## Outputs |Output|Type|Description| |------|----|-----------| |`changeBalances`|string|A string that contains the calculated amounts resulting from the exchange order.| |`errors`|string|Following a `400` error response, the error objects show information about the error that occurred. Contains a status code, message, and list of fields.| |`exchangeOrderSummaryId`|ID|The ID of the order summary record associated with the list of exchanges.| |`isSuccess`|boolean|The ID of the order summary record created for the exchanges.| |`orderSummaryID`|ID|The ID of the order summary record associated with the list of exchanges.| # Submit for Approval Actions Submit a Salesforce record for approval if an approval process is defined for the current entity. For more information about creating submit for approval actions, see [Creating Approval Actions](https://help.salesforce.com/HTViewHelpDoc?id=approvals_creating_approval_actions.htm), and to learn more about approval processes, see [Approval Process Overview](https://help.salesforce.com/apex/HTViewHelpDoc?id=what_are_approvals.htm&language=en_US), in Salesforce Help. This object is available in API version 32.0 and later. ## Supported REST HTTP Methods **URI:** Get a list of actions: `/services/data/vXX.X/actions/standard/submit` **Formats:** JSON, XML **HTTP Methods:** GET, HEAD, POST **Authentication:** `Authorization: Bearer token` ## Inputs |Input|Type|Description| |-----|----|-----------| |`comment`|string|Optional. Comments that accompany the Approval submission.| |`nextApproverIds`|reference|Optional. An array of one ID of the next approver, which can be a user or a group. This input is optional because some approval processes have the next approver specified in the approval process definition. You can't specify more than 2,000 approvers.| |`objectId`|reference|Required. The ID of the record being submitted for approval.| |`processDefinitionNameOrId`|string|Optional. The ID or name of the approval process to run against the record. If none is specified, the first approval process whose entry criteria the record satisfies is used. Names can't be longer than 120 characters.| |`skipEntryCriteria`|boolean|Optional. A Boolean value controlling whether the entry criteria for the specified approval process must be evaluated for the record (`true`) or not (`false`). If set to true, also specify `processDefinitionNameOrId`.| |`submitterId`|string|Optional. The ID of the user submitting the record for approval. If none is specified, the submitter is the current user.| ## Outputs |Output|Type|Description| |------|----|-----------| |`actorIds`|reference|An array of the IDs of the next approvers.| |`entityId`|reference|The ID of the record submitted for approval.| |`instanceId`|reference|The ID of the approval process instance.| |`instanceStatus`|string|The status of the approval: `Approved`, `Pending`, `Rejected`, or `Removed`.| |`newWorkItemIds`|reference|An array of the IDs of the work items created for the next step in this approval process.| # Submit, Approve, or Reject Process Approvals Submits a particular record both if its entity supports an approval process and the entity has a defined approval process. Records can be approved and rejected if the current user is an assigned approver. This resource is available in REST API version 30.0 and later. When using a POST request to do bulk approvals, the requests that succeed are committed and the requests that don’t succeed send back an error. ## Syntax **URI:** `/services/data/vXX.X/process/approvals/` **Formats:** JSON, XML **HTTP methods:** POST **Authentication:** `Authorization: Bearer token` **Request parameters:** None required **Request body** The request body contains an array of process requests that contain the following information: |Name|Type|Description| |----|----|-----------| |`actionType`|string|Represents the kind of action to take: Submit, Approve, or Reject.| |`contextActorId`|ID|The ID of the submitter who’s requesting the approval record.| |`contextId`|ID|The ID of the record to submit for approval.| |`comments`|string|The comment to add to the history step associated with this request.| |`nextApproverIds`|ID[]|If the process requires specification of the next approval, the ID of the user to be assigned the next request.| |`processDefinitionNameOrId`|string|The developer name or ID of the process definition.| |`skipEntryCriteria`|boolean|Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null. If the process definition name or ID isn’t specified, this argument is ignored, and standard evaluation is followed based on process order. By default, the entry criteria isn’t skipped if it’s not set by this request.| **Response body** The response contains an array of process results that contain the following information: |Name|Type|Description| |----|----|-----------| |`actorIds`|ID[]|IDs of the users who are currently assigned to this approval step.| |`entityId`|ID|The object being processed.| |`errors`|Error[]|The set of errors returned if the request failed.| |`instanceId`|ID|The ID of the ProcessInstance associated with the object submitted for processing.| |`instanceStatus`|string|The status of the current process instance (not an individual object but the entire process instance). The valid values are “Approved,” “Rejected,” “Removed,” or “Pending.”| |`newWorkItemIds`|ID[]|Case-insensitive IDs that point to ProcessInstanceWorkitem items (the set of pending approval requests)| |`success`|boolean|`true` if processing or approval completed successfully.| ## Example - See [Submit a Record for Approval](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-process-approvals-submit.md). - See [Approve a Record](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-process-approvals-approve.md). - See [Reject a Record](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-process-approvals-reject.md). - See [Bulk Approvals](https://developer.salesforce.com/docs/platform/api-rest/do-me/dome-process-approvals-bulk.md). # Subscribe and Unsubscribe from a Message Channel To subscribe and unsubscribe from a message channel, use the `sforce.one.subscribe()` and `sforce.one.unsubscribe()` methods. ## Example The `lmsSubscriberVisualforceRemoting` page from the [github.com/trailheadapps/lwc-recipes](https://github.com/trailheadapps/lwc-recipes) repo shows how to subscribe and unsubscribe from a message channel. The following example is a continuation of the example in [Publish on a Message Channel](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/message-channel-publish.md) that lets you subscribe and unsubscribe from a message channel when you click the respective button. In the JavaScript, we have the `subscribeMC()` and `unsubscribeMC()` methods, and `onMCPublished()` to populate the `textarea` with message output. Load the custom message channel `$MessageChannel.SampleMessageChannel__c` into the variable `SAMPLEMC`. The `$MessageChannel` global variable creates a unique token for the associated message channel. Under `SAMPLEMC`, we declare the variable `subscriptionToMC` that holds the subscription object returned from the `sforce.one.subscribe()` method. The `subscribeMC()` method checks whether the subscription object is empty. If it is, then it calls the `sforce.one.subscribe()` method. `sforce.one.subscribe()` has two parameters, the subscribing message channel, `onMCPublished()`, and the method that processes the message output. By default, communication over a message channel can occur only between components in an active navigation tab, an active navigation item, or a utility item. Utility items are always active. A navigation tab or item is active when it’s selected. Navigation tabs and items include: - Standard navigation tabs - Console navigation workspace tabs - Console navigations subtabs - Console navigation items To receive messages on a message channel from anywhere in the application, use the `sforce.one.subscribe()` method's optional fourth parameter, `subscriberOptions`. Set `scope` in the `subscriberOptions` to the value `"APPLICATION"`. ```apex sforce.one.subscribe(messageChannel, listener, {scope: "APPLICATION"}); ``` The `unsubscribeMC()` method checks whether there is a subscription object. If so, it calls `sforce.one.unsubscribe()`, and passes in the `subscriptionToMC` object. Then, it clears the `subscriptionToMC` object. The `onMCPublished()` method converts the message payload from a JSON object to a string. It then displays the message in the `textarea` with the ID `MCMessageTextArea`. ```nolang

    Subscribe to SampleMessageChannel

    Unsubscribe from subscription



    Received message:

    ``` **note:** This example uses the JavaScript toolkit Dojo, which you’ll need to upload as a static resource, reference from a CDN, or otherwise provide. For more information, see [http://dojotoolkit.org/](http://dojotoolkit.org/). # Working with Events in JavaScript These are useful and common patterns for working with events in JavaScript. Events communicate data across components. Events can contain attributes with values set before the event is fired and read when the event is handled. ## Fire an Event Fire a component event or an application event that’s registered on a component. ```javascript //Fire a component event var compEvent = cmp.getEvent("sampleComponentEvent"); compEvent.fire(); //Fire an application event var appEvent = $A.get("e.c:appEvent"); appEvent.fire(); ``` For more information, see: - [Fire Component Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-component-fire.md) - [Fire Application Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-application-fire.md) ## Get an Event Name To get the name of the event that’s fired: ```javascript event.getSource().getName(); ``` ## Get an Event Parameter To get an attribute that’s passed into an event: ```javascript event.getParam("value"); ``` ## Get Parameters on an Event To get all attributes that are passed into an event: ```javascript event.getParams(); ``` `event.getParams()` returns an object containing all event parameters. ## Get the Current Phase of an Event To get the current phase of an event: ```javascript event.getPhase(); ``` If the event hasn’t been fired, `event.getPhase()` returns `undefined`. Possible return values for component and application events are `capture`, `bubble`, and `default`. Value events return `default`. For more information, see: - [Component Event Propagation](https://developer.salesforce.com/docs/platform/aura-platform/events/events-component-propagation.md) - [Application Event Propagation](https://developer.salesforce.com/docs/platform/aura-platform/events/events-application-propagation.md) ## Get the Source Component To get the component that fired the event: ```javascript event.getSource(); ``` To retrieve an attribute on the component that fired the event: ```javascript event.getSource().get("v.myName"); ``` ## Pause the Event To pause the fired event: ```javascript event.pause(); ``` If paused, the event is not handled until `event.resume()` is called. You can pause an event in the `capture` or `bubble` phase only. For more information, see: - [Handling Bubbled or Captured Component Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-component-bubbling.md) - [Handling Bubbled or Captured Application Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-application-handling-phases.md) ## Prevent the Default Event Execution To cancel the default action on the event: ```javascript event.preventDefault(); ``` For example, you can prevent a `lightning:button` component from submitting a form when it’s clicked. ## Resume a Paused Event To resume event handling for a paused event: ```javascript event.resume(); ``` You can resume a paused event in the `capture` or `bubble` phase only. For more information, see: - [Handling Bubbled or Captured Component Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-component-bubbling.md) - [Handling Bubbled or Captured Application Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-application-handling-phases.md) ## Set a Value for an Event Parameter To set a value for an event parameter: ```javascript event.setParam("name", cmp.get("v.myName")); ``` If the event has already been fired, setting a parameter value has no effect on the event. ## Set Values for Event Parameters To set values for parameters on an event: ```javascript event.setParams({ key : value }); ``` If the event has already been fired, setting the parameter values has no effect on the event. ## Stop Event Propagation To prevent further propagation of an event: ```javascript event.stopPropagation(); ``` You can stop event propagation in the `capture` or `bubble` phase only. # Working with Field Sets You can use dynamic bindings to display field sets on your Visualforce pages. A field set is a grouping of fields. For example, you could have a field set that contains fields describing a user's first name, middle name, last name, and business title. If the page is added to a managed package, administrators can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code. Field sets are available for Visualforce pages on API version 21.0 or above. You can have up to 50 field sets referenced on a single page. An sObject can have up to 2,000 field sets. **note:** Each field set can have up to 25 fields through lookup relationships. Fields can only span one level away from the entity. ## Working with Field Sets Using Visualforce Field sets can be directly referenced in Visualforce by combining the `$ObjectType` global variable with the keyword `FieldSets`. For example, if your Contact object has a field set called `properNames` that displays three fields, your Visualforce page can reference the field data through the following iteration: ```visualforce
    ``` You can also choose to render additional information, such as field labels and data types, through the following special properties on the fields in the field set: |Property Name|Description| |-------------|-----------| |`DBRequired`|Indicates whether the field is required for the object| |`FieldPath`|Lists the field’s spanning info| |`Label`|The UI label for the field| |`Required`|Indicates whether the field is required in the field set| |`Type`|The data type for the field| For example, you can access the labels and data types for the fields in `properNames` like this: ```visualforce Name Label Data Type ``` If this Visualforce page is added to a managed package and distributed, subscribers can edit the `properNames` field set. The logic for generating the Visualforce page remains the same, while the presentation differs based on each subscriber’s implementation. To reference a field set from a managed package, you must prepend the field set with the organization’s namespace. Using the markup above, if `properNames` comes from an organization called Spectre, the field set is referenced like this: ```visualforce {!$ObjectType.Contact.FieldSets.Spectre__properNames} ``` ## Working with Field Sets Using Apex Fields in a field set are automatically loaded when your Visualforce page uses a standard controller. When using a custom controller, you need to add the required fields to the SOQL query for the page. Apex provides two Schema objects that allow you to discover field sets and the fields they contain, `Schema.FieldSet` and `Schema.FieldSetMember`. For information about these two system classes, see the [Lightning Platform Apex Code Developer's Guide](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_fieldsets_describe.htm). **Sample: Displaying a Field Set on a Visualforce Page** This sample uses `Schema.FieldSet` and `Schema.FieldSetMember` methods to dynamically get all the fields in the Dimensions field set for the Merchandise custom object. The list of fields is then used to construct a SOQL query that ensures those fields are available for display. The Visualforce page uses the `MerchandiseDetails` class as its controller. ```controller public with sharing class MerchandiseDetails { public Merchandise__c merch { get; set; } public MerchandiseDetails() { this.merch = getMerchandise(); } public List getFields() { return SObjectType.Merchandise__c.FieldSets.Dimensions.getFields(); } private Merchandise__c getMerchandise() { String query = 'SELECT '; for(Schema.FieldSetMember f : this.getFields()) { query += f.getFieldPath() + ', '; } query += 'Id, Name FROM Merchandise__c LIMIT 1'; return Database.query(query, AccessLevel.USER_MODE); } } ``` The Visualforce page using the above controller is simple: ```markup ``` One thing to note about the above markup is the expression used to determine if a field on the form should be indicated as being a required field. A field in a field set can be required by either the field set definition, or the field’s own definition. The expression handles both cases. ## Field Set Considerations Fields added to a field set can be in one of two categories: The order in which a developer lists displayed fields determines their order of appearance on a Visualforce page. As a package developer, keep the following best practices in mind: - Subscribers with installed field sets can add fields that your page didn’t account for. There is no way to conditionally omit some fields from a field set iteration, so make sure that any field rendered through your field set works for all field types. - We recommend that you add only non-essential fields to your field set. This ensures that even if a subscriber removes all fields in the field set, Visualforce pages that use that field set still function. **note:** Field sets are available for Visualforce pages on API version 21.0 or above. **See Also** - [$FieldSet](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/variables/pages-variables-global-fieldset.md) - [Object Schema Details Available Using $ObjectType](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/variables/pages-variables-global-objecttype-schema-objects-reference.md) - [*Salesforce Help*: Creating and Editing Field Sets](https://help.salesforce.com/articleView?id=fields_editing_field_sets.htm&type=5) # Working with Large Sets of Data Visualforce custom controllers and controller extensions are subject to Apex governor limits. For more information about governor limits. Additionally, Visualforce iteration components, such as `` and ``, are limited to a maximum of 1,000 items in the collection they iterate over. Sometimes your Visualforce pages may need to work with or display larger sets of data, but not need to make modifications to that data; for example, if you are providing custom reporting and analytics. Visualforce offers developers a “read-only mode”, which relaxes the limit on the number of rows which can be queried in one request, and increases the limit on the number of collection items which can be iterated over within the page. You can specify read-only mode either for an entire page or, with certain limitations, on individual components or methods. **note:** You can only iterate over large sets of data if you specify read-only mode for the entire page. - **[Setting Read-Only Mode for an Entire Page](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-readonly-context-pagelevel.md)** To enable read-only mode for an entire page, set the `readOnly` attribute on the `` component to `true`. - **[Setting Read-Only Mode for Controller Methods](https://developer.salesforce.com/docs/platform/salesforce-pages-developers-guide/guide/pages-controller-readonly-context-methodlevel.md)** Visualforce controller methods can, with some important limitations, use the Apex `ReadOnly` annotation, even if the page itself isn’t in read-only mode. # Working with Lightning Base Components Lightning base components are the building blocks that make up the modern user interfaces in Lightning Experience, Salesforce app, and Experience Builder sites. Base components incorporate Lightning Design System markup and classes, providing improved performance and accessibility with a minimum footprint. These base components handle the details of HTML and CSS for you. Each component provides simple attributes that enable variations in style. This means that you typically don’t need to use CSS at all. The simplicity of the base Lightning component attributes and their clean and consistent definitions make them easy to use, enabling you to focus on your business logic. You can find base Lightning components in the `lightning` namespace to complement the existing `ui` namespace components. In instances where there are matching `ui` and `lightning` namespace components, we recommend that you use the `lightning` namespace component. The `lightning` namespace components are optimized for common use cases. Beyond being equipped with the Lightning Design System styling, they handle accessibility, real-time interaction, and enhanced error messages. **note:** Components in the lightning namespace are available as Aura components and Lightning web components. We recommend using Lightning web components whenever possible. Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning web components and Aura components can coexist and interoperate on a page. These components are part of the Lightning Component framework. See the [Lightning Web Components (LWC) Developer Guide](https://developer.salesforce.com/docs/component-library/documentation/lwc) for more information. Base components are available for use with LWC. To migrate your base components, see [Migrate `ui` components](https://developer.salesforce.com/docs/platform/lwc/guide/migrate-map-ui-components.html). While the base components are visual building blocks and provides minimum functionality out-of-the-box, they can be combined together to build “experience components” with richer capabilities and made accessible via the Lightning App Builder. Admins can drag-and-drop these experience components to build and configure user interfaces easily. For example, the Chatter Feed component in Lightning App Builder comprises a collection of tabs, a group of buttons, and a rich text editor. The API version column denotes the minimum API version you must set to use the component in the Developer Console, the Salesforce Extensions for Visual Studio Code, or via API. Components that don’t specify a minimum API version are usable with any API version 37.0 and later. **note:** Interactive examples for the following components are available in the [Lightning Component Library](https://developer.salesforce.com/docs/platform/aura-platform/components/component-library.md). ## Buttons These components provide different button flavors. | Type | Aura Component Name | Description | SLDS 1 | API Version | | ---------------------- | ------------------------------ | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | ----------- | | Button | `lightning:button` | Represents a button element. | [Buttons](https://v1.lightningdesignsystem.com/components/buttons/) | | | Button Group | `lightning:buttonGroup` | Represents a group of buttons. | [Button Groups](https://v1.lightningdesignsystem.com/components/button-groups/) | | | Button Icon | `lightning:buttonIcon` | An icon-only HTML button. | [Button Icons](https://v1.lightningdesignsystem.com/components/button-icons/) | | | Button Icon (Stateful) | `lightning:buttonIconStateful` | An icon-only button that retains state. | [Button Icons](https://v1.lightningdesignsystem.com/components/button-icons/) | 41.0 | | Button Menu | `lightning:buttonMenu` | A dropdown menu with a list of actions or functions. | [Menus](https://v1.lightningdesignsystem.com/components/menus) | | | | `lightning:menuItem` | A list item in `lightning:buttonMenu`. | | | | | `lightning:menuDivider` | A horizontal line separating menu items in `lightning:buttonMenu`. | | | | | `lightning:menuSubheader` | A subheading for menu items in `lightning:buttonMenu`. | | | | Button Stateful | `lightning:buttonStateful` | A button that toggles between states. | [Button Stateful](https://v1.lightningdesignsystem.com/components/buttons#Stateful) | | | Insert Image Button | `lightning:insertImageButton` | A button for inserting images in `lightning:inputRichText`. | [Button Icons](https://v1.lightningdesignsystem.com/components/button-icons/) | 43.0 | ## Data Entry Use these components for data entry. | Type | Lightning Component Name | Description | SLDS 1 | API Version | | ---------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | Address | `lightning:inputAddress` | Represents an address compound field. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 42.0 | | Checkbox Group | `lightning:checkboxGroup` | Enables single or multiple selection on a group of options. | [Checkbox](https://v1.lightningdesignsystem.com/components/checkbox/) | 41.0 | | Combobox | `lightning:combobox` | An input element that enables single selection from a list of options. | [Combobox](https://v1.lightningdesignsystem.com/components/combobox/) | | | Dual Listbox | `lightning:dualListbox` | Provides an input listbox accompanied with a listbox of selectable options. Options can be moved between the two lists. | [Dueling Picklist](https://v1.lightningdesignsystem.com/components/dueling-picklist/) | 41.0 | | File Uploader and Preview | `lightning:fileUpload` | Enables file uploads to a record. | [File Selector](https://v1.lightningdesignsystem.com/components/file-selector/) | 41.0 | | | `lightning:fileCard` | Displays a representation of uploaded content. | [Files](https://v1.lightningdesignsystem.com/components/files/) | | | Input | `lightning:input` | Represents interactive controls that accept user input depending on the type attribute. | [Input](https://v1.lightningdesignsystem.com/components/input/) | | | Input Field | `lightning:inputField` | Represents an editable input for a field on a Salesforce object. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 42.0 | | Input Name | `lightning:inputName` | Represents a name compound field. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 42.0 | | Input Location (Geolocation) | `lightning:inputLocation` | A geolocation compound field that accepts a latitude and longitude value. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 41.0 | | Radio Group | `lightning:radioGroup` | Enables single selection on a group of options. | [Radio Button](https://v1.lightningdesignsystem.com/components/radio-group/)

    [Radio Button Group](https://v1.lightningdesignsystem.com/components/radio-button-group/) | 41.0 | | Select | `lightning:select` | Creates an HTML `select` element. | [Select](https://v1.lightningdesignsystem.com/components/select) | | | Slider | `lightning:slider` | An input range slider for specifying a value between two specified numbers. | [Slider](https://v1.lightningdesignsystem.com/components/slider) | 41.0 | | Rich Text Area | `lightning:inputRichText` | A WYSIWYG editor with a customizable toolbar for entering rich text. | [Rich Text Editor](https://v1.lightningdesignsystem.com/components/rich-text-editor) | | | Text Area | `lightning:textArea` | A multiline text input. | [Textarea](https://v1.lightningdesignsystem.com/components/textarea/#site-main-content) | | ## Displaying Data Use these components to display data. | Type | Lightning Component Name | Description | SLDS | API Version | | ------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------- | ---- | ----------- | | Address | `lightning:formattedAddress` | Displays a formatted address that provides a link to the given location on Google Maps. | N/A | 42.0 | | Click-to-dial | `lightning:clickToDial` | | | | | Date/Time | `lightning:formattedDateTime` | Displays formatted date and time. | | | | Email | `lightning:formattedEmail` | Displays an email as a hyperlink with the `mailto:` URL scheme. | | 41.0 | | Geolocation | `lightning:formattedLocation` | Displays a geolocation using the format `latitude, longitude`. | | 41.0 | | Name | `lightning:formattedName` | Displays a formatted name that can include a salutation and suffix. | | 42.0 | | Number | `lightning:formattedNumber` | Displays formatted numbers. | | | | Output Field | `lightning:outputField` | Displays a label, help text, and value for a field on a Salesforce object. | | 41.0 | | Phone | `lightning:formattedPhone` | Displays a phone number as a hyperlink with the `tel:` URL scheme. | | 41.0 | | Rich Text | `lightning:formattedRichText` | Displays rich text that’s formatted with allowed tags and attributes. | | 41.0 | | Text | `lightning:formattedText` | Displays text, replaces newlines with line breaks, and linkifies if requested. | | 41.0 | | Time | `lightning:formattedTime` | Displays a formatted time based on the user’s locale. | | 42.0 | | URL | `lightning:formattedUrl` | Displays a URL as a hyperlink. | | 41.0 | | Relative Date/Time | `lightning:relativeDateTime` | Displays the relative time difference between the source date-time and the provided date-time. | | | ## Forms Use these components to edit and view records. | Type | Lightning Component Name | Description | SLDS 1 | API Version | | ---------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ----------- | | Record Edit Form | `lightning:recordEditForm` | A grouping of `lightning:inputField` components of record fields to be edited in a form. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 42.0 | | Record Form | `lightning:recordForm` | A container to simplify form creation for viewing and editing record fields. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 43.0 | | Record View Form | `lightning:recordViewForm` | A grouping of `lightning:outputField` components and other formatted display components to display record fields in a form. | [Form Elements](https://v1.lightningdesignsystem.com/components/form-element/) | 42.0 | ## Layout The following components group related information together. | Type | Lightning Component Name | Description | SLDS 1 | API Version | | --------- | ---------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------- | ----------- | | Accordion | `lightning:accordion` | A collection of vertically stacked sections with multiple content areas. | [Accordion](https://v1.lightningdesignsystem.com/components/accordion/) | 41.0 | | | `lightning:accordionSection` | A single section that is nested in a l`lightning:accordion` component. | | | | Card | `lightning:card` | Applies a container around a related grouping of information. | [Cards](https://v1.lightningdesignsystem.com/components/cards/) | | | Carousel | `lightning:carousel` | A collection of images that are displayed horizontally one at a time. | [Carousel](https://v1.lightningdesignsystem.com/components/carousel/) | 42.0 | | Layout | `lightning:layout` | Responsive grid system for arranging containers on a page. | [Grid](https://v1.lightningdesignsystem.com/utilities/grid) | | | | `lightning:layoutItem` | A container within a `lightning:layout` component. | | | | Tabs | `lightning:tab` | A single tab that is nested in a `lightning:tabset` component. | [Tabs](https://v1.lightningdesignsystem.com/components/tabs/) | | | | `lightning:tabset` | Represents a list of tabs. | | | | Tile | `lightning:tile` | A grouping of related information associated with a record. | [Tiles](https://v1.lightningdesignsystem.com/components/tiles/) | | ## Navigation Components The following components organize links and actions in a hierarchy or to visit other locations in an app. | Type | Lightning Component Name | Description | SLDS 1 | API Version | | ------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ----------- | | Breadcrumb | `lightning:breadcrumb` | An item in the hierarchy path of the page the user is on. | [Breadcrumbs](https://v1.lightningdesignsystem.com/components/breadcrumbs/) | | | | `lightning:breadcrumbs` | A hierarchy path of the page you're currently visiting within the website or app. | | | | Navigation | `lightning:navigation` | Generates a URL for a page reference. | N/A | 43.0 | | Map | `lightning:map` | Displays a map of one or more locations | [Map](https://v1.lightningdesignsystem.com/components/map/) | 44.0 | | Tree | `lightning:tree` | Displays a structural hierarchy with nested items. | [Trees](https://v1.lightningdesignsystem.com/components/trees/) | 41.0 | | Vertical Navigation | `lightning:verticalNavigation` | A vertical list of links that take you to another page or parts of the page you’re in. | [Vertical Navigation](https://v1.lightningdesignsystem.com/components/vertical-navigation/) | 41.0 | | | `lightning:verticalNavigationItem` | A text-only link within `lightning:verticalNavigationSection` or `lightning:verticalNavigationOverflow` | | | | | `lightning:verticalNavigationItemBadge` | A link and badge within `lightning:verticalNavigationSection` or `lightning:verticalNavigationOverflow` | | | | | `lightning:verticalNavigationItemIcon` | A link and icon within `lightning:verticalNavigationSection` or `lightning:verticalNavigationOverflow` | | | | | `lightning:verticalNavigationOverflow` | An overflow of items in `lightning:verticalNavigation` | | | | | `lightning:verticalNavigationSection` | A section within `lightning:verticalNavigation` | | | ## Visual Components The following components provide informative cues, for example, like icons and loading spinners. | Type | Lightning Component Name | Description | SLDS 1 | API Version | | --------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | Avatar | `lightning:avatar` | A visual representation of an object. | [Avatars](https://v1.lightningdesignsystem.com/components/avatar/) | | | Badge | `lightning:badge` | A label that holds a small amount of information. | [Badges](https://v1.lightningdesignsystem.com/components/badges/) | | | Data Table | `lightning:datatable` | A table that displays columns of data, formatted according to type. | [Data Tables](https://v1.lightningdesignsystem.com/components/data-tables/) | 41.0 | | Dynamic Icon | `lightning:dynamicIcon` | A variety of animated icons. | [Dynamic Icons](https://v1.lightningdesignsystem.com/components/dynamic-icons/) | 41.0 | | Help Text (Tooltip) | `lightning:helptext` | An icon with a popover container a small amount of text. | [Tooltips](https://v1.lightningdesignsystem.com/components/tooltips/) | | | Icon | `lightning:icon` | A visual element that provides context. | [Icons](https://v1.lightningdesignsystem.com/components/icons/) | | | List View | `lightning:listView` | Displays a list view of the specified object | N/A | 42.0 | | Messaging | `lightning:overlayLibrary` | Displays messages via modals and popovers. | [Messaging](https://v1.lightningdesignsystem.com/guidelines/messaging/overview/) | 41.0 | | | `lightning:notificationsLibrary` | Displays messages via notices and toasts. | [Messaging](https://v1.lightningdesignsystem.com/guidelines/messaging/overview/) | 41.0 | | Path | `lightning:path` | Displays a path driven by a picklist field and Path Setup metadata. | [Path](https://v1.lightningdesignsystem.com/components/path/) | 41.0 | | Picklist Path | `lightning:picklistPath` | Displays a path based on a specified picklist field. | | | | Pill | `lightning:pill` | A pill represents an existing item in a database, as opposed to user-generated freeform text. | [Pills](https://v1.lightningdesignsystem.com/components/pills) | | | Pill Container | `lightning:pillContainer` | A list of pills grouped in a container. | [Pills](https://v1.lightningdesignsystem.com/components/pills) | 42.0 | | Progress Bar | `lightning:progressBar` | A horizontal progress bar from left to right to indicate the progress of an operation. | [Progress Bars](https://v1.lightningdesignsystem.com/components/progress-bar/) | 41.0 | | Progress Indicator and Path | `lightning:progressIndicator` | Displays steps in a process to indicate what has been completed. | [Progress Indicators](https://v1.lightningdesignsystem.com/components/progress-indicator/)

    [Path](https://v1.lightningdesignsystem.com/components/path/) | 41.0 | | Tree Grid | `lightning:treeGrid` | A hierarchical view of data presented in a table. | [Trees](https://v1.lightningdesignsystem.com/components/trees/) | 42.0 | | Spinner | `lightning:spinner` | Displays an animated spinner. | [Spinners](https://v1.lightningdesignsystem.com/components/spinners/) | | ## Feature-Specific Components The following components are usable only in the context of specific Salesforce features. | Type | Lightning Component Name | Description | SLDS | API Version | | ----------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------- | ---- | ----------- | | Lightning Page Region | `lightning:flexipageRegionInfo` | Provides Lightning page region information to the component that contains it. | N/A | 41.0 | | Flow Interview | `lightning:flow` | Represents a flow interview in Lightning runtime. | | 41.0 | | Omni-Channel Toolkit | `lightning:omniToolkitAPI` | Provides API access to methods for the Omni-channel toolkit. | | 41.0 | | Lightning Console Utility Bar | `lightning:utilityBarAPI` | Provides API access to methods for the utility bar in Lightning Console. | | 41.0 | | Lightning Console Workspace | `lightning:workspaceAPI` | Provides API access to methods for the workspace in Lightning Console. | | 41.0 | | Embedded Chat | `lightningsnapin:prechatAPI` | Enables customization of the user interface for the pre-chat page. | | 42.0 | | Embedded Chat | `lightningsnapin:settingsAPI` | Provides API access to Embedded Service settings within your custom Embedded Service components. | | 43.0 | | Embedded Chat | `lightningsnapin:minimizedAPI` | Enables customization of the user interface for the minimized chat window for Embedded Chat. | | 43.0 | | EmpJs Streaming API library | `lightning:empApi` | Provides access to methods for subscribing to a streaming channel and listening to event messages | | 44.0 | # Working with Lightning Design System Variants Base component variants correspond to blueprint variations in Lightning Design System. Variants change the appearance of a component and are controlled by the `variant` attribute. ## Applying Variants to Base Components Variants on a component refer to design variations for that component, which enable you to change the appearance of the component easily. We try to create variants for each component to apply the design of variations and examples from the SLDS component blueprint. However, not all variants are implemented yet. Most base components provide a `variant` attribute that accepts two or more variants. For example, `lightning:button` supports many variants to apply different text and background colors on the buttons. This example creates a button with the brand variant. ```nolang ``` If you don’t specify a variant or you pass in a variant that’s not supported, the default variant is used instead. For button, the neutral variant is used by default. Some components don’t support a `variant` attribute, but you can use Lightning Design System classes to achieve the styling you want. This example uses a Lightning Design System class to apply a padding to a paragraph in the `lightning:card` component. ```nolang

    Card Body with a Lightning Design System class

    ``` If you don’t find a variant you need, see if you can pass in a Lightning Design System class to the base component before creating your own custom CSS class. Don’t be afraid to experiment with Lightning Design System classes and variants in base components. For more information, see [Lightning Design System](https://www.lightningdesignsystem.com/components/overview). **note:** Interactive examples for base components are available in the [Lightning Component Library](https://developer.salesforce.com/docs/platform/aura-platform/components/component-library.md). # Working with Object Metadata The examples in this section use REST API resources to retrieve object metadata information. For modifying or creating object metadata information, see the Metadata API Developer Guide. - **[Get Metadata for an Object](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-sobject-basic-info.md)** Use the sObject Basic Information resource to get metadata for an object. - **[Get Field and Other Metadata for an Object](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-sobject-describe.md)** Use the sObject Describe resource to retrieve all the metadata for an object, including information about each field, URLs, and child relationships. - **[Get Object Metadata Changes](https://developer.salesforce.com/docs/platform/api-rest/guide/sobject-describe-with-ifmodified-header.md)** Use the sObject Describe resource and the `If-Modified-Since` HTTP header to determine if object metadata has changed. # Working with PushTopics Each PushTopic record that you create corresponds to a channel in CometD. The channel name is the name of the PushTopic prefixed with “/topic/”, for example, `/topic/MyPushTopic`. A Bayeux client can receive streamed events on this channel. The channel name is case-sensitive when you subscribe. As soon as a PushTopic record is created, the system starts evaluating record creates, updates, deletes, and undeletes for matches. Whenever there’s a match, a new notification is generated. The server polls for new notifications for currently subscribed channels every second. This frequency can fluctuate depending on the overall server load. **note:** - Record changes that Bulk API performs don’t generate notifications because a large volume of changes can flood a channel. Also, changes made by tools that use Bulk API, such as the Mass Transfer tool or Data Loader, don’t generate notifications. - Cascade-deleted records don't trigger PushTopic notifications. To receive notifications for cascade-deleted records, use Change Data Capture instead. For more information, see [Change Data Capture Developer Guide](https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm). The PushTopic defines when notifications are generated in the channel. Specify the conditions in these PushTopic fields: - [PushTopic Queries](https://developer.salesforce.com/docs/platform/api-streaming/guide/pushtopic-queries.md) - [Events](https://developer.salesforce.com/docs/platform/api-streaming/events-and-notifications/events.md) - [Notifications](https://developer.salesforce.com/docs/platform/api-streaming/events-and-notifications/notifications.md) To receive notifications, users must have read access on the object in the PushTopic query and the PushTopic itself. **note:** PushTopic isn’t available for users in Experience Cloud sites, including Partner Community and Customer Community users. Also, PushTopic isn’t available in legacy Customer Portals. # Working with Recently Viewed Information The examples in this section use REST API Query and Recently Viewed resources to programmatically retrieve and update recently viewed record information. - **[View Recently Viewed Records](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-see-recently-viewed.md)** Use the Recently Viewed Items resource to get a list of recently viewed records. - **[Mark Records as Recently Viewed](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-mark-records-as-recently-viewed.md)** To mark a record as recently viewed using REST API, use the Query resource with a `FOR VIEW` or `FOR REFERENCE` clause. Use SOQL to mark records as recently viewed to ensure that information such as the date and time the record was viewed is correctly set. # Working with Records The examples in this section use REST API resources to create, retrieve, update, and delete records, along with other record-related operations. - **[Create a Record](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-sobject-create.md)** Use the sObject Basic Information resource to create new records. You supply the required field values in the request data, and send the request using the POST HTTP method. The response body contains the ID of the new record if the call is successful. - **[Update a Record](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-update-fields.md)** You use the sObject Rows resource to update records. Provide the updated record information in your request data and use the PATCH method of the resource with a specific record ID to update that record. Records in a single file must be of the same object type. - **[Delete a Record](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-delete-record.md)** Use the sObject Rows resource to delete records. Specify the record ID and use the DELETE method of the resource to delete a record. - **[Get Field Values from a Standard Object Record](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-field-values.md)** You use the GET method of the sObject Rows resource to retrieve field values from a record. - **[Get Field Values from an External Object Record by Using the Salesforce ID](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-field-values-external-object-hdv.md)** You use the sObject Rows resource to retrieve field values from a record. Specify the fields you want to retrieve in the `fields` parameter and use the GET method of the resource. - **[Get Field Values from an External Object Record by Using the External ID Standard Field](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-field-values-external-object.md)** You use the sObject Rows resource to retrieve field values from a record. Specify the fields you want to retrieve in the `fields` parameter and use the GET method of the resource. - **[Get a Record Using an External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/using-resources-retrieve-with-externalid.md)** You can use the GET method of the sObject Rows by External ID resource to get records with a specific external ID. - **[Insert or Update (Upsert) a Record Using an External ID](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-upsert.md)** You can use the sObject Rows by External ID resource to create records or update existing records (upsert) based on the value of a specified external ID field. - **[Traverse Relationships with Friendly URLs](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-relationship-traversal.md)** You can traverse relationship fields in standard and custom objects by constructing friendly URLs using the sObject Relationship resource. This approach allows you to directly access records associated by relationships. Using friendly URLs is an easier alternative to accessing records by obtaining object IDs from relationship fields and then inspecting the associated object ID record. - **[Get a List of Deleted Records Within a Given Timeframe](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-deleted.md)** Use the sObject Get Deleted resource to get a list of deleted records for the specified object. Specify the date and time range within which the records for the given object were deleted. Deleted records are written to a delete log (that is periodically purged), and will be filtered out of most operations, such as sObject Rows or Query (although QueryAll will include deleted records in results). - **[Get a List of Updated Records Within a Given Timeframe](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-updated.md)** Use the sObject Get Updated resource to get a list of updated (modified or added) records for the specified object. Specify the date and time range within which the records for the given object were updated. # Working with Salesforce Data To create, read, and update Salesforce data from an Aura component, use Lightning Data Service via `force:recordData` or the form-based components. To delete Salesforce data, use `force:recordData`. - **[Lightning Data Service](https://developer.salesforce.com/docs/platform/aura-platform/guide/data-service.md)** Use Lightning Data Service to load, create, edit, or delete a record in your component without requiring Apex code. Lightning Data Service handles sharing rules and field-level security for you. In addition to simplifying access to Salesforce data, Lightning Data Service improves performance and user interface consistency. - **[Using Apex](https://developer.salesforce.com/docs/platform/aura-platform/apex/apex-intro.md)** Use Apex to write server-side code, such as controllers and test classes. Use Apex only if you need to customize your user interface to do more than what Lightning Data Service allows, such as using a SOQL query to select certain records. Apex provisions data that’s not managed and you must handle data refresh on your own. # Working with Searches and Queries The examples in this section use REST API resources to search and query records using Salesforce Object Search Language (SOSL) and Salesforce Object Query Language (SOQL), and other search APIs. For more information on SOSL and SOQL see the [SOQL and SOSL Reference](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/). - **[Execute a SOQL Query](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-query.md)** Use the Query resource to execute a SOQL query that returns all the results in a single response, or if needed, returns part of the results and a locator used to retrieve the remaining results. - **[Execute a SOQL Query that Includes Deleted Items](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-queryall.md)** Use the QueryAll resource to execute a SOQL query that includes information about records that have been deleted because of a merge or delete. Use QueryAll rather than Query, because the Query resource will automatically filter out items that have been deleted. - **[Get Feedback on Query Performance (Beta)](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-query-explain.md)** To get feedback on how Salesforce executes your query, report, or list view, use the Query resource along with the `explain` parameter. Salesforce analyzes each query to find the optimal approach to obtain the query results. Depending on the query and query filters, Salesforce uses an index or internal optimization. To return details on how Salesforce optimizes your query, without actually running the query, use the `explain` parameter. Based on the response, decide whether to fine-tune the performance of your query, like adding filters to make the query more selective. - **[Search for a String](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-search.md)** Use the Search resource to execute a SOSL search or use the Parameterized Search resource to execute a simple RESTful search without SOSL. - **[Get the Default Search Scope and Order](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-retrieve-search-scope-order.md)** Use the Search Scope and Order resource to retrieve the default global search scope and order for the logged-in user, including any pinned objects in the user’s search results page. - **[Get Search Result Layouts for Objects](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-retrieve-search-layouts.md)** Use the Search Result Layouts resource to retrieve the search result layout configuration for each object specified in the query string. - **[Get Relevant Items](https://developer.salesforce.com/docs/platform/api-rest/guide/dome-get-relevant-items.md)** Use the Relevant Items resource to retrieve a list of relevant items. # Working with the AJAX Toolkit Most JavaScript that you add to Visualforce pages, buttons, or links has three sections: first, connecting to the AJAX Toolkit, next, embedding the API methods in JavaScript, and finally, processing the results. This section explains each of these steps. - **[Connecting to the API](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-connecting.md)** The first portion of any JavaScript code that uses the AJAX Toolkit must make the toolkit available to the JavaScript code. The syntax for this is different depending on whether you are embedding JavaScript in a Visualforce page, or a button or link. - **[Embedding API Calls in JavaScript](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-embedding.md)** - **[Processing Results](https://developer.salesforce.com/docs/platform/ajax/guide/sforce-api-ajax-results.md)** # Workspace Setup Set up your development environment, create a project to develop your LWC in, and connect your project to Salesforce. 1. Launch VS Code. 2. Select **File** | **Open** and open a project to use with your org. **note:** If you don’t have a project created, you can open the VS Code Command Palette by clicking **View** | **Command Palette**, enter `SFDX`, and select **SFDX: Create a Project**. Then follow the prompts. 3. In the menu bar, select **View** | **Terminal** to open VS Code’s integrated terminal if it’s not already visible. 4. Run the following command to install the Salesforce Extension Plugins for mobile. ```javascript sf plugins install @salesforce/lwc-dev-mobile ``` 5. In the menu bar, select **View** | **Command Palette** to open the VS Code Command Palette. 6. Enter `SFDX` and select **SFDX: Authorize an Org**. 7. Select the org you want to use and press **Enter**. A web page opens for the org login. 8. Verify your org authorization by checking the bottom left in VS Code. You should see your username in the VS Code status bar. ![VS Code status bar showing org authentication status](https://developer.salesforce.com/media/mobile-offline/qs_action_vscode_auth.png) If you have difficulty authorizing SFDX for access to your org, see [SFDX Authorization](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth.htm). # Write Aura Component Accessibility Tests When you develop with Aura components, you can use Salesforce’s test tools to check for common accessibility issues. You can call Aura accessibility tests in two environments. - For JavaScript tests, use `$A.test.assertAccessible()`. - For WebDriver tests, use `auraTestingUtil.assertAccessible()`. These functions check the rendered DOM elements to make sure they pass Salesforce’s accessibility validation. When you use these tools, there are two outcomes: pass or fail. If the tool doesn’t find any accessibility exceptions, it returns an empty string. If the tool does find accessibility exceptions, it returns the accessibility rule that failed, the erroneous tag, and a stack trace of where it was found in the code. Since Aura components and pages are dynamic, make sure to retest your components’ accessibility every time something changes in the DOM. Otherwise you aren’t checking every UI state your users encounter. The Aura accessibility tests look for these issues: - Images without `alt` attributes - Anchor elements without textual content - `input` elements without associated labels - Radio button groups not in `fieldset` tags - `iframe` or `frame` elements with empty `title` attributes - `fieldset` elements without `legend` tags - `th` element without a `scope` attribute - `head` element with an empty `title` attribute - Headings (`H1`, `H2`, and so forth) increasing by more than one level at a time - CSS color contrast ratio between text and background less than 4.5:1 These tests aren’t all-encompassing. If your code passes every test, it’s not a guarantee that your product is fully accessible. However, these tests do surface major accessibility issues, and ensure that your code remains accessible. - **[Accessibility Tests Example](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-tests-example.md)** 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. - **[Other Accessibility Automation Tools](https://developer.salesforce.com/docs/platform/aura-platform/guide/accessibility-tools.md)** There are a number of robust open-source tools and mobile test frameworks for testing for accessibility. # Write Efficient Apex and SOQL To improve the overall performance of a Visualforce page, write efficient Apex and SOQL. When you write Apex or SOQL for use within a Visualforce page: - Perform calculations in SOQL instead of in Apex whenever possible. - Never perform Data Manipulation Language (DML) operations inside a loop. - Filter in SOQL first, then in Apex, and finally in Visualforce. **See Also** - [*Apex Developer Guide*: Working with Data in Apex](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_data_intro.htm) - [*Apex Developer Guide*: Working with Very Large SOQL Queries](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_VLSQ.htm) - [*SOQL and SOSL Reference*](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_sosl_intro.htm) # Write Efficient Getter Methods Visualforce requests evaluate expressions, action attributes, and other method calls. A request such as a form submission can call the getter methods in a class multiple times. With more efficient getter methods, you can prevent unnecessary lookups of the same record. To reduce the processing load of each request, cache the value of a property calculation so that additional calls can access the property without recalculating the value. You can also configure the getter methods in your Apex classes to only query for data if the object is null. For example, the following code snippet returns the Account record associated with the page. On the first method call, the method queries for the record because the MyAccount object is null. On subsequent calls, it returns the object’s stored value, which prevents additional identical `SELECT` queries: ```apex Account MyAccount; public Account getMyAccount() { if (MyAccount == null) { MyAccount = [SELECT name, annualRevenue FROM Account WHERE id = :ApexPages.currentPage().getParameters(). get('id')]; } return MyAccount; } ``` **See Also** - [Defining Getter Methods](https://developer.salesforce.com/docs/platform/quick-start/advanced/pages-quick-start-controller-getter-methods.md) # Writing Documentation for the Component Library Documentation helps developers use your components to develop their apps more effectively. You can provide interactive examples, documentation, and specification descriptions for a component, event, or interface. Each component, event, or interface has a root definition that defines the element’s metadata, as well as attributes, events, or methods. ## Component A component’s root definition is specified in the `` tag contained in componentName.cmp, as described in [Component Markup](https://developer.salesforce.com/docs/platform/aura-platform/components/components-markup.md). ## Event An event’s root definition is specified in the `` tag contained in componentEvent.evt, as described in [Create Custom Component Events](https://developer.salesforce.com/docs/platform/aura-platform/events/events-component-create.md). ## Interface An interface’s root definition is specified in the `` tag contained in the interfaceName.intf, as described in [Interfaces](https://developer.salesforce.com/docs/platform/aura-platform/oo/oo-interfaces.md). The root definition tag determines whether the element is exposed in the [Component Library](https://developer.salesforce.com/docs/platform/aura-platform/components/component-library.md). You provide the documentation for each element in an .auradoc file that accompanies the other files that define the component, event, or interface. ## Viewing the Documentation View the Component Library through your org at https://_MyDomainName_.my.salesforce.com/docs/component-library. Alternatively, view the unauthenticated Component Library at https://developer.salesforce.com/docs/component-library/. For namespaces that you own, elements with either `access="global"` or `access="public"`(default) are surfaced in the Component Library when it’s accessed through your org. In the unauthenticated Component Library, only the elements with `access="global"` are visible. For managed package namespaces, only elements with `access="global"` are surfaced in the Component Library. Elements with `access="public"` can be used only by components in the same namespace in the same org. They aren’t available to other orgs that install the package, so they aren’t surfaced in the Component Library. Only global components in managed packages are visible because they are intended for use in any namespace in any org. Each element can display up to three tabs in the following order. ### Example Displays interactive examples denoted by the `` tag in the `.auradoc` file. This tab is hidden if no examples are wired up in your `.auradoc` file. This tab is not supported if your component has dependency on org data, such as with `lightning:recordForm`. ### Documentation Displays the content of the `.auradoc` file. This tab is hidden if an `.auradoc` file is not available for your component, event, or interface. ### Specification Displays the description of the root definition, attributes, and methods. For namespaces you own, attributes and methods with either `access="global"` or `access="public"`(default) are surfaced in the Component Library when it’s accessed through your org. For managed package namespaces, only `access="global"` attributes and methods are visible. - **[Creating Examples](https://developer.salesforce.com/docs/platform/aura-platform/guide/docs-examples.md)** Examples are interactive and help others learn about a component, event, or interface. - **[Creating Documentation Content](https://developer.salesforce.com/docs/platform/aura-platform/guide/docs-auradoc.md)** Documentation provides usage guidelines and code samples about a component, event, or interface. - **[Providing Specification Information and Descriptions](https://developer.salesforce.com/docs/platform/aura-platform/guide/docs-specs.md)** Descriptions on the **Specification** tab describes a root definition and its attributes and methods. **See Also** - [Controlling Access](https://developer.salesforce.com/docs/platform/aura-platform/access/access-intro.md)