Let us know so we can improve!
Class: AnalyticsMetric
A web component for embedding a Tableau Next metric.
| Methods | Accessors | Properties |
|---|---|---|
Export
AnalyticsMetric
Extends
AnalyticsComponentWithFilter
Implements
ExportableFilterSimplification
Constructors
new AnalyticsMetric()
new AnalyticsMetric(
props):AnalyticsMetric
The constructor for the AnalyticsMetric.
Parameters
• props: MetricProps
The properties for the AnalyticsMetric component.
Returns
Usage
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
9analyticsEventTarget.addEventListener(EventName.ERROR, (errorEvent) => { //Listening to global ERROR event, such as SDK or component initialization failures.
10 console.log("Received a global error event", errorEvent) //Error details, such as error code and message, are available in the event object
11});
12
13await initializeAnalyticsSdk({ //Configuration object for initializing the Tableau Next Embedding SDK
14 authCredential: "<%- authCredential %>", //The frontdoor URL required for authentication
15 orgUrl: '<%- org-url %>' //The Salesforce org URL that hosts the Analytics component to embed.
16});
17
18const analyticsMetric = new AnalyticsMetric({
19 parentIdOrElement: '<%- parent-element %>', //The parent ID or element to render the component in
20 idOrApiName: '<%- metric-id-or-api-name %>' //The ID or API name of the component to embed
21});
22
23analyticsMetric.addEventListener(EventName.ERROR, (event) => { //Listening to component specific ERROR event
24 console.log("Received error", event); //Error details (such as error code and message) are available in the event object
25 });
26
27analyticsMetric.addEventListener(EventName.COMPONENT_LOADED, () => { //Listening to COMPONENT_LOADED event triggered when the component gets loaded
28 console.log("Component Loaded");
29});
30
31analyticsMetric.filters = [ //Sets filter property of the component to apply a filter on the embedded metric
32 {
33 fieldName: '<%- semantic-model-api-name %>.<%- field-api-name %>', //The API name of the semantic model and the API name of the field to filter
34 values: ['<%- value %>'], //The field value to filter the component with based on the operator <%filter-operator %>
35 operator: FilterOperator.<%filter-operator %>
36 }
37];
38
39analyticsMetric.range = {
40 operator: FilterOperator.<%filter-operator %>, //The date range specific operators to apply on the metric
41 values: ['<%- value %>'], //The value may or may not be required for the date range based on the operator <%filter-operator %>
42}
43
44analyticsMetric.render(); //Renders the metric card in the parent HTML element1//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
11analyticsEventTarget.addEventListener(EventName.ERROR, (errorEvent) => { //Listening to global ERROR event, such as SDK or component initialization failures.
12 console.log("Received a global error event", errorEvent) //Error details, such as error code and message, are available in the event object
13});
14
15const config: AnalyticsSdkConfig = { //Configuration object for initializing the Tableau Next Embedding SDK
16 authCredential: "<%- authCredential %>", //The frontdoor URL required for authentication
17 orgUrl: "<%- org-url %>" //The Salesforce org URL that hosts the Analytics component to be embedded.
18};
19await initializeAnalyticsSdk(config); //Initializes the Tableau Next Embedding SDK with the provided configuration and returns a promise that resolves on successful initialization.
20
21const metricProps: MetricProps = { // Defines the properties required for configuring a metric card component.
22 parentIdOrElement: '<%- parent-element %>', //The parent ID or element to render the component in
23 idOrApiName: '<%- metric-id-or-api-name %>', //The ID or API name of the component to embed
24};
25
26const analyticsMetric: AnalyticsMetric = new AnalyticsMetric(metricProps); //A web component for embedding an analytics metric card
27
28analyticsMetric.addEventListener(EventName.ERROR, (event) => { //Listening to component specific ERROR event
29 console.log("Received error", event); //Error details (such as error code and message) are available in the event object
30});
31
32analyticsMetric.addEventListener(EventName.COMPONENT_LOADED, () => { //Listening to COMPONENT_LOADED event triggered when the component gets loaded
33 console.log("Component Loaded");
34});
35
36analyticsMetric.filters = [ //Sets filter property of the component to apply a filter on the embedded metric
37 {
38 fieldName: '<%- semantic-model-api-name %>.<%- field-api-name %>', //The API name of the semantic model and the API name of the field to filter
39 values: ['<%- value %>'], //The field value to filter the component with based on the operator <%filter-operator %>
40 operator: FilterOperator.<%filter-operator %>
41 }
42];
43
44analyticsMetric.range = {
45 operator: FilterOperator.<%filter-operator %>, //The date range specific operators to apply on the metric
46 values: ['<%- value %>'], //The value may or may not be required for the date range based on the operator <%filter-operator %>
47}
48
49analyticsMetric.render(); //Renders the metric card in the parent HTML elementMulti-org Usage
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 orgUrl: "https://org1.lightning.force.com", // Required in multi-org
6});
7
8const metric2 = new AnalyticsMetric({
9 parentIdOrElement: "container2",
10 idOrApiName: "Metric2",
11 orgUrl: "https://org2.lightning.force.com", // Required in multi-org
12});Note: The orgUrl parameter must be a Lightning URL (e.g., https://yourorg.lightning.force.com), not the my.salesforce.com domain URL. All methods of the component operate on the org specified by this orgUrl.
Overrides
AnalyticsComponentWithFilter.constructor
Properties
parentIdOrElement
parentIdOrElement:
string|HTMLElement
This ID of the container or the container where the analytics component is embedded.
Inherited from
AnalyticsComponentWithFilter.parentIdOrElement
Accessors
borderRadius
getborderRadius():string
The border radius for the component, in CSS units. Acceptable string formats include:
- Pixel values (e.g., “5px”)
- Percentages (e.g., “50%”)
- Relative units (e.g., “1em”, “0.5rem”)
- Other valid CSS border-radius values (e.g., “10px 5px”, “50% / 10%”) If an invalid or empty value is provided, default border-radius is applied.
setborderRadius(val):void
Parameters
• val: string
Returns
string
- Returns the border radius value as a CSS string.
componentType
getcomponentType():string
Returns the component type: ‘metric’.
Returns
string
Overrides
AnalyticsComponentWithFilter.componentType
filters
getfilters():UnifiedFilterJson[]
The filters for the component.
setfilters(val):void
Sets the filters for the component.
Parameters
• val: UnifiedFilterJson[]
The filters to set.
Returns
- Returns a list of filters for the component.
Inherited from
AnalyticsComponentWithFilter.filters
height
getheight():string
The height for the component, in CSS units. Acceptable string formats include:
- Pixel values (e.g., “800px”)
- Percentages (e.g., “100%”)
- Relative units (e.g., “2rem”, “1.5em”)
- Other valid CSS height values. If an invalid value is provided, the value defaults to 100%.
setheight(val):void
Parameters
• val: string
Returns
string
- Returns the height of the component.
Inherited from
AnalyticsComponentWithFilter.height
idOrApiName
getidOrApiName():string
The ID or API name used to identify the Tableau Next component.
setidOrApiName(val):void
Parameters
• val: string
Returns
string
- Returns the ID or API name of the component to embed.
Inherited from
AnalyticsComponentWithFilter.idOrApiName
layout
getlayout():MetricLayoutAttributes
Returns the metric layout.
setlayout(val):void
Set the layout attributes for the metric.
Parameters
• val: MetricLayoutAttributes
The layout attributes for the metric.
Returns
- The metric layout, if defined.
orgUrl
getorgUrl():undefined|string
The org URL for the component.
Multi-org Note: In multi-org scenarios, this property identifies which org the component belongs to. Returns a Lightning URL (e.g., https://yourorg.lightning.force.com).
setorgUrl(val):void
Parameters
• val: string
Returns
undefined | string
The org URL, or undefined if not set.
Inherited from
AnalyticsComponentWithFilter.orgUrl
range
setrange(val):void
Sets the time range to display for the metric data. This controls the period of time for the rendered metric values.
Parameters
• val: FilterCondition
The time range for the metric.
width
getwidth():string
The width for the component, in CSS units. Acceptable string formats include:
- Pixel values (e.g., “800px”)
- Percentages (e.g., “100%”)
- Relative units (e.g., “2rem”, “1.5em”)
- Other valid CSS width values. If an invalid value is provided, the value defaults to 100%.
setwidth(val):void
Parameters
• val: string
Returns
string
- Returns the width of the component.
Inherited from
AnalyticsComponentWithFilter.width
Methods
applyFilters()
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.
Parameters
• filters: UnifiedFilterJson[]
A list of filters.
Returns
Promise<void>
- A promise that resolves when the filters are applied.
Async
Examples
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 {
8 fieldName: "Account.Name",
9 operator: FilterOperator.Equals,
10 values: ["Acme Corp"],
11 dataSource: "SalesData", // specifying data source for dashboards
12 },
13];
14
15await component.applyFilters(filters); //applies the filters to the component.1// For metrics or visualizations, dataSource not needed.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [
6 {
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 },
11];
12
13await component.applyFilters(filters); //applies the filters to the component.Inherited from
AnalyticsComponentWithFilter.applyFilters
applyLayout()
applyLayout(
layout):Promise<void>
Applies a metric layout to the component asynchronously. Use this to show or hide specific parts of the metric.
Parameters
• layout: MetricLayoutAttributes
The metric layout to apply.
Returns
Promise<void>
- A promise that resolves when the layout has been applied.
Example
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()
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.
Parameters
• 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.
Returns
Promise<void>
- A promise that resolves when the time range has been applied.
Async
Example
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()
clearFilters():
Promise<void>
Clears the current list of filters for the component.
Returns
Promise<void>
A promise that resolves when the fliters are removed.
Async
Examples
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 {
8 fieldName: "Account.Name",
9 operator: FilterOperator.Equals,
10 values: ["Acme Corp"],
11 dataSource: "SalesData",
12 },
13];
14
15await component.applyFilters(filters); //applies the filters to the component.
16
17await component.clearFilters(); // Clears the filters applied to the component.1// For metrics or visualizations, no need to pass dataSource.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [
6 {
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 },
11];
12
13await component.applyFilters(filters); //applies the filters to the component.
14
15await component.clearFilters(); // Clears the filters applied to the component.Inherited from
AnalyticsComponentWithFilter.clearFilters
clearTimeRange()
clearTimeRange():
Promise<void>
Clears the current time range for the component.
Returns
Promise<void>
A promise that resolves when the time range is removed.
Async
Example
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()
export(
filename?,filetype?):Promise<void>
Triggers an event requesting an export of the component in the required format.
Parameters
• filename?: string
The name of the file to export, excluding the file extension. If not provided, the componentName is used.
• filetype?: ExportFileType
The format of export. If not provided, defaults to PNG. Supported types: PNG.
Returns
Promise<void>
A promise that resolves when the export operation is complete.
Async
Throws
Throws an error if the export operation isn’t supported.
Example
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 supportedImplementation of
Exportable.export
getFields()
getFields(
dataSources?):Promise<Map<string,Field[]>>
Returns a map of fields associated with the component.
Parameters
• dataSources?: DataSource[]
A list of datasources to retrieve the fields from. This isn’t required for visualizations and metrics. If omitted for dashboards, fields for all available data sources will be returned.
Returns
Promise<Map<string, Field[]>>
- A promise that resolves to a map where each key is a string data source API name and value is an array of Field objects.
Example
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// }Implementation of
FilterSimplification.getFields
getFilterFieldValues()
getFilterFieldValues(
fieldApiName,fieldObjectName?,searchTerm?):Promise<any>
Retrieves the values for a specified field.
Parameters
• 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.
Returns
Promise<any>
A promise that resolves with the field values. The exact structure depends on the event handler.
Example
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// ]Implementation of
FilterSimplification.getFilterFieldValues
getFilters()
getFilters():
Promise<UnifiedFilterJson[]>
Returns the list of filters applied to the component.
Returns
Promise<UnifiedFilterJson[]>
A promise that resolves to a list of FilterInfo objects.
Async
Examples
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 {
8 fieldName: "Account.Name",
9 operator: FilterOperator.Equals,
10 values: ["Acme Corp"],
11 dataSource: "SalesData",
12 },
13];
14
15await component.applyFilters(filters); //applies the filters to the component.
16const appliedFilters = await component.getFilters(); // Returns the filters applied to the component.1// For metrics or visualizations, no need to pass dataSource.
2
3await component.render();
4
5const filters: UnifiedFilterJson[] = [
6 {
7 fieldName: "Account.Name",
8 operator: FilterOperator.Equals,
9 values: ["Acme Corp"],
10 },
11];
12
13await component.applyFilters(filters); //applies the filters to the component.
14const appliedFilters = await component.getFilters(); // Returns the filters applied to the component.Inherited from
AnalyticsComponentWithFilter.getFilters
getInteractionDetails()
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
Returns
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 objects
Async
Example
1// Example response structure for metric or visualization:
2// {
3// fields: Map {
4// "SalesData" => [
5// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" },
6// { apiName: "Region", label: "Region", dataType: "String", fieldType: "Dimension" }
7// ]
8// },
9// filterFields: Map {
10// "SalesData" => [
11// { apiName: "Amount", label: "Amount", dataType: "Number", fieldType: "Measure" }
12// ]
13// }
14// }Implementation of
FilterSimplification.getInteractionDetails
getLayout()
getLayout():
Promise<MetricLayoutAttributes>
Returns the layout of the component asynchronously.
Returns
Promise<MetricLayoutAttributes>
- A promise that resolves with the MetricLayoutAttributes object.
Example
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()
getTimeRange():
Promise<FilterCondition>
Returns the time range applied to the component.
Returns
Promise<FilterCondition>
A promise that resolves to time range applied to the component.
Async
Example
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.getTimeRange(); // Returns 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.reload()
reload():
Promise<void>
Reloads the component to retrieve the latest data from the server.
Returns
Promise<void>
- A promise that resolves when reload is complete.
Async
Inherited from
AnalyticsComponentWithFilter.reload
render()
render():
Promise<string>
Renders the component by appending it to the specified parent element.
Returns
Promise<string>
A promise that resolves when the component is loaded successfully, or rejects with an error message if the loading fails.
Inherited from
AnalyticsComponentWithFilter.render
Let us know so we can improve!