Let us know so we can improve!
The online Trailblazer Community is now read-only. [Read the FAQ] [Get Help]
A web component for embedding a Tableau Next metric.
AnalyticsMetric
AnalyticsComponentnew AnalyticsMetric(
props):AnalyticsMetric
The constructor for the AnalyticsMetric.
• props: MetricProps
The properties for the AnalyticsMetric component.
1//JavaScript
2//Importing required modules and libraries from the Tableau Next Embedding SDK
3import {
4 AnalyticsMetric,
5 initializeAnalyticsSdk,
6 analyticsEventTarget
7} from '@salesforce/analytics-embedding-sdk';
8
9//Listening to global ERROR event, such as SDK or component initialization failures.
10analyticsEventTarget.addEventListener(EventName.ERROR, (errorEvent) => {
11 //Error details (such as error code and message) are available in the event object
12 console.log("Received a global error event", errorEvent)
13});
14
15//Configuration object for initializing the Tableau Next Embedding SDK
16await initializeAnalyticsSdk({
17 //The frontdoor URL required for authentication
18 authCredential: "<%- authCredential %>",
19 //The Salesforce org URL that hosts the Analytics component to embed.
20 orgUrl: '<%- org-url %>'
21});
22
23const analyticsMetric = new AnalyticsMetric({
24 //The parent ID or element to render the component in
25 parentIdOrElement: '<%- parent-element %>',
26 //The ID or API name of the component to embed
27 idOrApiName: '<%- metric-id-or-api-name %>'
28});
29
30//Listening to component specific ERROR event
31analyticsMetric.addEventListener(EventName.ERROR, (event) => {
32 //Error details (such as error code and message) are available in the event object
33 console.log("Received error", event);
34});
35
36//Listening to COMPONENT_LOADED event triggered when the component gets loaded
37analyticsMetric.addEventListener(EventName.COMPONENT_LOADED, () => {
38 console.log("Component Loaded");
39});
40
41//Sets filter property of the component to apply a filter on the embedded metric
42analyticsMetric.filters = [
43 {
44 //The API name of the semantic model and the API name of the field to filter
45 fieldName: '<%- semantic-model-api-name %>.<%- field-api-name %>',
46 //The field value to filter the component with based on the operator <%filter-operator %>
47 values: ['<%- value %>'],
48 operator: FilterOperator.<%filter-operator %>
49 }
50];
51
52analyticsMetric.range = {
53 //The date range specific operators to apply on the metric
54 operator: FilterOperator.<%filter-operator %>,
55 //The value may or may not be required for the date range based on the operator <%filter-operator %>
56 values: ['<%- value %>']
57}
58//Renders the metric card in the parent HTML element
59analyticsMetric.render();1//TypeScript
2//Importing required modules and libraries from the Tableau Next Embedding SDK
3import {
4 AnalyticsMetric,
5 initializeAnalyticsSdk,
6 analyticsEventTarget,
7 type MetricProps,
8 type AnalyticsSdkConfig
9} from '@salesforce/analytics-embedding-sdk';
10
11//Listening to global ERROR event, such as SDK or component initialization failures.
12analyticsEventTarget.addEventListener(EventName.ERROR, (errorEvent) => {
13 //Error details (such as error code and message) are available in the event object
14 console.log("Received a global error event", errorEvent)
15});
16
17//Configuration object for initializing the Tableau Next Embedding SDK
18const config: AnalyticsSdkConfig = {
19 //The frontdoor URL required for authentication
20 authCredential: "<%- authCredential %>",
21 //The Salesforce org URL that hosts the Analytics component to be embedded.
22 orgUrl: "<%- org-url %>"
23};
24//Initializes the Tableau Next Embedding SDK with the provided configuration and returns a promise that resolves on successful initialization
25await initializeAnalyticsSdk(config); .
26
27// Defines the properties required for configuring a metric card component.
28const metricProps: MetricProps = {
29 //The parent ID or element to render the component in
30 parentIdOrElement: '<%- parent-element %>',
31 //The ID or API name of the component to embed
32 idOrApiName: '<%- metric-id-or-api-name %>'
33};
34
35//A web component for embedding an analytics metric card
36const analyticsMetric: AnalyticsMetric = new AnalyticsMetric(metricProps);
37
38//Listening to component specific ERROR event
39analyticsMetric.addEventListener(EventName.ERROR, (event) => {
40 //Error details (such as error code and message) are available in the event object
41 console.log("Received error", event);
42});
43
44//Listening to COMPONENT_LOADED event triggered when the component gets loaded
45analyticsMetric.addEventListener(EventName.COMPONENT_LOADED, () => {
46 console.log("Component Loaded");
47});
48
49//Sets filter property of the component to apply a filter on the embedded metric
50analyticsMetric.filters = [
51 {
52 //The API name of the semantic model and the API name of the field to filter
53 fieldName: '<%- semantic-model-api-name %>.<%- field-api-name %>',
54 //The field value to filter the component with based on the operator <%filter-operator %>
55 values: ['<%- value %>'],
56 operator: FilterOperator.<%filter-operator %>
57 }
58];
59
60analyticsMetric.range = {
61 //The date range specific operators to apply on the metric
62 operator: FilterOperator.<%filter-operator %>,
63 //The value may or may not be required for the date range based on the operator <%filter-operator %>
64 values: ['<%- value %>']
65}
66
67//Renders the metric card in the parent HTML element
68analyticsMetric.render();In multi org scenarios, always specify the orgUrl parameter when creating components:
1// After initializing SDK with multiple orgs
2const metric1 = new AnalyticsMetric({
3 parentIdOrElement: 'container1',
4 idOrApiName: 'Metric1',
5 // Required in multi-org
6 orgUrl: 'https://org1.lightning.force.com'
7});
8
9const metric2 = new AnalyticsMetric({
10 parentIdOrElement: 'container2',
11 idOrApiName: 'Metric2',
12 // Required in multi-org
13 orgUrl: 'https://org2.lightning.force.com'
14});The orgUrl parameter must be a Lightning URL (e.g., https://yourorg.lightning.force.com), not the my.salesforce.com domain URL.
Note
AnalyticsComponent.constructor
parentIdOrElement:
string|HTMLElement
This ID of the container or the container where the analytics component is embedded.
AnalyticsComponent.parentIdOrElement
getborderRadius():string
The border radius for the component, in CSS units. Acceptable string formats include:
If an invalid or empty value is provided, default border-radius is applied.
setborderRadius(val):void
• val: string
string
getcomponentType():string
Returns the component type: ‘metric’.
string
AnalyticsComponent.componentType
getfilters():UnifiedFilterJson[]
The filters for the component.
setfilters(val):void
• val: UnifiedFilterJson[]
AnalyticsComponent.filters
getheight():string
The height for the component, in CSS units. Acceptable string formats include:
If an invalid value is provided, the value defaults to 100%.
setheight(val):void
• val: string
string
AnalyticsComponent.height
getidOrApiName():string
The ID or API name used to identify the Tableau Next component.
setidOrApiName(val):void
• val: string
string
AnalyticsComponent.idOrApiName
getlayout():MetricLayoutAttributes
Returns the metric layout.
setlayout(val):void
Set the layout attributes for the metric.
• val: MetricLayoutAttributes
The layout attributes for the metric.
getorgUrl():undefined|string
The org URL for the component.
In multi-org scenarios, this property identifies which org the component belongs to. Returns a Lightning URL (e.g., https://yourorg.lightning.force.com).
Note
setorgUrl(val):void
• val: string
undefined | string
The org URL, or undefined if not set.
AnalyticsComponent.orgUrl
setrange(val):void
Sets the time range to display for the metric data. This controls the period of time for the rendered metric values.
• val: FilterCondition
The time range for the metric.
getwidth():string
The width for the component, in CSS units. Acceptable string formats include:
If an invalid value is provided, the value defaults to 100%.
setwidth(val):void
• val: string
string
AnalyticsComponent.width
applyFilters(
filters):Promise<void>
Apply the specified filters to the component.
If the filter format is invalid, an ERROR event is thrown and the filter application fails.
Please ensure that all filters are correctly formatted and have correct values for the required properties.
• filters: UnifiedFilterJson[]
A list of filters.
Promise<void>
1// For dashboards, the `dataSource` attribute is required in the filter input
2// to specify the data source to which the filter should be applied.
3
4await component.render();
5
6const filters: UnifiedFilterJson[] = [{
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 // specifying data source for dashboards
11 dataSource: "SalesData"
12}];
13
14//applies the filters to the component.
15await component.applyFilters(filters);1// For metrics or visualizations, dataSource not needed.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [{
6 fieldName: "Account.Name",
7 operator: FilterOperator.Equals,
8 values: ["Acme Corp"]
9}];
10
11//applies the filters to the component.
12await component.applyFilters(filters);AnalyticsComponent.applyFilters
applyLayout(
layout):Promise<void>
Applies a metric layout to the component asynchronously. Use this to show or hide specific parts of the metric.
• layout: MetricLayoutAttributes
The metric layout to apply.
Promise<void>
1const metric = new AnalyticsMetric({
2 parentIdOrElement: 'metric-container',
3 idOrApiName: 'my-metric'
4});
5
6await metric.render();
7
8const layout: MetricLayoutAttributes = {
9 "componentVisibility": {
10 "details": true,
11 "title": true,
12 "value": true,
13 "comparison": true,
14 "chart": true,
15 "insights": true,
16 "menu": true,
17 "badge": true
18 }
19}
20
21await metric.applyLayout(layout);applyTimeRange(
timeRange):Promise<void>
Apply the specified time range to the metric component.
If the time range filter format is invalid, an ERROR event is thrown and the time range filter application fails. Please ensure the filter is correctly formatted and has correct values for the required properties.
• timeRange: FilterCondition
A MetricTimeRange object representing the time range to apply.
Must include a valid operator, and optionally a values array depending on the operator.
Promise<void>
1const metric = new AnalyticsMetric({
2 parentIdOrElement: 'metric-container',
3 idOrApiName: 'my-metric'
4});
5
6await metric.render();
7
8const timeRange: MetricTimeRange = {
9 "operator": "PreviousYear"
10}
11
12await metric.applyTimeRange(timeRange);
13
14// Examples of valid time range filter formats:
15// { "operator": "Yesterday" }
16// { "operator": "LastNDays", values: [30] }
17// { "operator": "CurrentYearToDate" }
18// { "operator" : "Between" , "values" : ["2019-06-26","2023-07-07"] }
19// etc.clearFilters():
Promise<void>
Clears the current list of filters for the component.
Promise<void>
A promise that resolves when the filters are removed.
1// For dashboards, the `dataSource` attribute is required in the filter input
2// to specify the data source to which the filter should be applied.
3
4await component.render();
5
6const filters: UnifiedFilterJson[] = [{
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 dataSource: "SalesData"
11}];
12
13//applies the filters to the components
14await component.applyFilters(filters);
15
16// Clears the filters applied to the component.
17await component.clearFilters();1// For metrics or visualizations, no need to pass dataSource.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [{
6 fieldName: "Account.Name",
7 operator: FilterOperator.Equals,
8 values: ["Acme Corp"]
9}];
10
11//applies the filters to the component.
12await component.applyFilters(filters);
13
14// Clears the filters applied to the component.
15await component.clearFilters();AnalyticsComponent.clearFilters
clearTimeRange():
Promise<void>
Clears the current time range for the component.
Promise<void>
A promise that resolves when the time range is removed.
1const metric = new AnalyticsMetric({
2 parentIdOrElement: 'metric-container',
3 idOrApiName: 'my-metric'
4});
5
6await metric.render();
7
8const timeRange: MetricTimeRange = {
9 "operator": "PreviousYear"
10}
11
12await metric.applyTimeRange(timeRange);
13
14await metric.clearTimeRange(); // Clears the time range applied to the component.
15
16// Examples of valid time range filter formats:
17// { "operator": "Yesterday" }
18// { "operator": "LastNDays", values: [30] }
19// { "operator": "CurrentYearToDate" }
20// { "operator" : "Between" , "values" : ["2019-06-26","2023-07-07"] }
21// etc.export(
filename?,filetype?):Promise<void>
Triggers an event requesting an export of the component in the required format.
• filename?: string
The name of the file to export, excluding the file extension. If not provided, the componentName is used.
• filetype?: ExportFileType = ExportFileType.PNG
The format of export. If not provided, defaults to PNG. Supported types: PNG.
Promise<void>
A promise that resolves when the export operation is complete.
Throws an error if the export operation isn’t supported.
1// Assuming `myComponent` is an instance of a class that implements the export() method
2// Export with default filename and default PNG format
3await myComponent.export();
4
5// Export with a custom filename (still as PNG)
6await myComponent.export("my-component");
7
8// Export with custom filename and file type
9await myComponent.export("report", ExportFileType.PNG); // Currently only PNG supportedAnalyticsComponent.export
getFields(
dataSources?):Promise<Map<string,Field[]>>
Returns a map of fields associated with the component.
• dataSources?: DataSource[]
A list of data sources to retrieve the fields from. This isn’t required for visualizations and metrics. If omitted for dashboards, fields for all available data sources are returned.
Promise<Map<string, Field[]>>
and value is an array of Field objects.
1// For dashboards, specify one or more data sources or omit to get all:
2// returns fields for all data sources
3const fieldsMap = await component.getFields();
4
5// Example response structure:
6// fieldsMap => Map {
7// "SalesData" => [
8// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" },
9// { apiName: "Region", label: "Region", dataType: "Text", fieldType: "Dimension" }
10// ],
11// "MarketingData" => [
12// { apiName: "CampaignName", label: "Campaign Name", dataType: "Text", fieldType: "Dimension" }
13// ]
14// }1// For metrics or visualizations, no need to pass dataSources, will return map for the single underlying data source:
2const fieldsMap = await component.getFields();
3
4// Example response structure:
5// fieldsMap => Map {
6// "SalesData" => [
7// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" },
8// { apiName: "Region", label: "Region", dataType: "Text", fieldType: "Dimension" }
9// ]
10// }AnalyticsComponent.getFields
getFilterFieldValues(
fieldApiName,fieldObjectName?,searchTerm?):Promise<any>
Retrieves the values for a specified field.
• fieldApiName: string
Required. The API name of the field to retrieve the values for.
• fieldObjectName?: string
The object name of the field.
The fieldObjectName parameter is only required if the specified field has an associated object name.
User can know whether field has an associated object name or not in the response of getFields().
• searchTerm?: string
Optional. A search term to filter the field values.
Promise<any>
A promise that resolves with the field values. The exact structure depends on the event handler.
1const fieldValues = await component.getFilterFieldValues("Account", "AccountObject", "Acme");
2console.log(fieldValues);
3
4// Example response:
5// [
6// "Acme Corporation",
7// "Acme Inc.",
8// "Acme Solutions"
9// ]AnalyticsComponent.getFilterFieldValues
getFilters():
Promise<UnifiedFilterJson[]>
Returns the list of filters applied to the component.
Promise<UnifiedFilterJson[]>
A promise that resolves to a list of FilterInfo objects.
1// For dashboards, the `dataSource` attribute is required in the filter input
2// to specify the data source to which the filter should be applied.
3
4await component.render();
5
6const filters: UnifiedFilterJson[] = [{
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 dataSource: "SalesData"
11}];
12
13//applies the filters to the component.
14await component.applyFilters(filters);
15// Returns the filters applied to the component.
16const appliedFilters = await component.getFilters();1// For metrics or visualizations, no need to pass dataSource.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [{
6 fieldName: "Account.Name",
7 operator: FilterOperator.Equals,
8 values: ["Acme Corp"]
9}];
10
11//applies the filters to the component.
12await component.applyFilters(filters);
13// Returns the filters applied to the component.
14const appliedFilters = await component.getFilters();AnalyticsComponent.getFilters
getInteractionDetails():
Promise<InteractionDetails>
Returns a comprehensive map containing all available data sources, fields, and filter fields for the component. This method provides a complete overview of the component.
Note: The dataSources array is only available for DashboardComponent
Promise<InteractionDetails>
A promise that resolves to an InteractionDetails object containing:
dataSources: Array of available data sourcesfields: Map where each key is a string data source API name and value is an array of Field objectsfilterFields: Map where each key is a string data source API name and value is an array of filterable Field objects1const interactionDetails = await component.getInteractionDetails();
2
3// Example response structure for dashboard:
4// {
5// dataSources: [
6// { apiName: "SalesData", label: "Sales Data Source" },
7// { apiName: "MarketingData", label: "Marketing Data Source" }
8// ],
9// fields: Map {
10// "SalesData" => [
11// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" },
12// { apiName: "Region", label: "Region", dataType: "String", fieldType: "Dimension" }
13// ],
14// "MarketingData" => [
15// { apiName: "CampaignName", label: "Campaign Name", dataType: "String", fieldType: "Dimension" }
16// ]
17// },
18// filterFields: Map {
19// "SalesData" => [
20// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" }
21// ],
22// "MarketingData" => [
23// { apiName: "CampaignName", label: "Campaign Name", dataType: "String", fieldType: "Dimension" }
24// ]
25// }
26// }
27
28// Example response structure for metric or visualization:
29// {
30// fields: Map {
31// "SalesData" => [
32// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" },
33// { apiName: "Region", label: "Region", dataType: "String", fieldType: "Dimension" }
34// ]
35// },
36// filterFields: Map {
37// "SalesData" => [
38// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" }
39// ]
40// }
41// }AnalyticsComponent.getInteractionDetails
getLayout():
Promise<MetricLayoutAttributes>
Returns the layout of the component asynchronously.
Promise<MetricLayoutAttributes>
MetricLayoutAttributes object.1const metric = new AnalyticsMetric({
2 parentIdOrElement: 'metric-container',
3 idOrApiName: 'my-metric'
4});
5
6await metric.render();
7
8await metric.getLayout(); // Returns the layout of the component.
9
10// Example of MetricLayoutAttributes object returned:
11// {
12// "componentVisibility": {
13// "details": true,
14// "title": true,
15// "value": true,
16// "comparison": true,
17// "chart": true,
18// "insights": true,
19// "menu": true,
20// "badge": true
21// }
22// }getTimeRange():
Promise<FilterCondition>
Returns the time range applied to the component.
Promise<FilterCondition>
A promise that resolves to time range applied to the component.
1const metric = new AnalyticsMetric({
2 parentIdOrElement: 'metric-container',
3 idOrApiName: 'my-metric'
4});
5
6await metric.render();
7
8const timeRange: MetricTimeRange = {
9 "operator": "PreviousYear"
10}
11
12await metric.applyTimeRange(timeRange);
13
14// Returns the time range applied to the component.
15await metric.getTimeRange();
16
17// Examples of valid time range filter formats:
18// { "operator": "Yesterday" }
19// { "operator": "LastNDays", values: [30] }
20// { "operator": "CurrentYearToDate" }
21// { "operator" : "Between" , "values" : ["2019-06-26","2023-07-07"] }
22// etc.reload():
Promise<void>
Reloads the component to retrieve the latest data from the server.
Promise<void>
AnalyticsComponent.reload
render():
Promise<string>
Renders the component by appending it to the specified parent element.
Promise<string>
A promise that resolves when the component is loaded successfully, or rejects with an error message if the loading fails.
AnalyticsComponent.render