Analytics Designer Developer Handbook
Analytics Designer Developer Handbook
Developer Handbook
Table of Contents
Table of Contents .........................................................................................................................1
Figures ..........................................................................................................................................8
6.2 Selecting Measures via Dropdown or Radio Button to Filter Table and Chart to
Display (Single Selection) ..............................................................................................116
6.3 Selecting Measures via Dropdown to Filter Table and Chart to Display (Multi-
Selection) .......................................................................................................................123
6.4 Using Filter Line for Filtering Table, Chart, and R Visualization ....................................133
6.5 Cascaded Filtering .........................................................................................................139
6.6 Add and Remove Dimension in Rows and Columns for Table ......................................146
6.7 Creating a Settings Panel Using a Popup Window........................................................167
6.8 Selection Handling in a Table or Chart and Open a Details Popup...............................186
6.9 Using R Widget Word Cloud for Visualization ...............................................................208
6.10 Set User Input for Planning Data ...................................................................................228
7 Planning ........................................................................................................................230
7.1 What to Expect from Analytics Designer Regarding Planning?.....................................230
7.2 Basic Planning Concepts in Analytics Designer ............................................................230
7.3 Refreshing Your Data ....................................................................................................232
7.4 Set User Input ................................................................................................................232
7.5 Planning Versions ..........................................................................................................233
7.5.1 Private Versions .............................................................................................................233
7.5.2 Public Versions ..............................................................................................................233
7.6 How to Manage Versions ...............................................................................................234
7.6.1 Publishing and Reverting Data Changes .......................................................................234
7.6.2 Copy ...............................................................................................................................236
7.7 Data Locking ..................................................................................................................236
7.7.1 Using getDataLocking() .................................................................................................237
7.7.2 Using getState() .............................................................................................................237
7.7.3 Using setState() .............................................................................................................238
7.8 Planning Events .............................................................................................................239
7.8.1 BpcPlanningSequence ...................................................................................................239
7.8.2 DataActionTrigger ..........................................................................................................239
7.9 Members on the Fly .......................................................................................................239
8 Predictive ......................................................................................................................241
8.1 Time Series Forecast .....................................................................................................241
8.1.1 Switch On and Off Forecast ...........................................................................................241
8.1.2 Configure Forecast ........................................................................................................241
8.2 Smart Insights ................................................................................................................242
8.2.1 Discover per Selected Data Point ..................................................................................242
8.3 Smart Grouping ..............................................................................................................243
8.3.1 Switch On and Off Smart Grouping ...............................................................................243
8.3.2 Configure Smart Grouping .............................................................................................244
8.4 Smart Discovery .............................................................................................................244
8.5 Search To Insight ...........................................................................................................245
9 OData.............................................................................................................................249
9.1 What You Should Know About OData ...........................................................................249
Table of Contents 6
Figures
Figure 1: Bookmark Component in Outline ..................................................................................17
Figure 2: Side Panel of Bookmark Component ............................................................................17
Figure 3: Turn on Translation .......................................................................................................18
Figure 4: Export to PDF Component in Outline ...........................................................................19
Figure 5: Side Panel of Export to PDF Component .....................................................................19
Figure 6: Side Panel of Export to PDF Component to Configure the Settings ............................20
Figure 7: Create a Story from a Widget .......................................................................................22
Figure 8: Create Application .........................................................................................................24
Figure 9: Edit Sharing Settings ....................................................................................................24
Figure 10: Open in View Mode .....................................................................................................25
Figure 11: Run Analytic Application .............................................................................................26
Figure 12: Fullscreen....................................................................................................................26
Figure 13: Save & Leave Dialog ..................................................................................................27
Figure 14: Outline .........................................................................................................................28
Figure 15: Context Menu for Scripting Objects in Outline ............................................................29
Figure 16: Context Menu for Canvas Objects in Outline ..............................................................29
Figure 17: Widget Name ..............................................................................................................30
Figure 18: Analytics Designer Properties .....................................................................................30
Figure 19: Dropdown Menu Style .................................................................................................30
Figure 20: Filter Menu Style .........................................................................................................31
Figure 21: Visual Feedback of Mouse Click & Hover ...................................................................31
Figure 22: Settings of Icon ...........................................................................................................31
Figure 23: Type of Button .............................................................................................................31
Figure 24: Actions Menu ..............................................................................................................32
Figure 25: Quick Menu Options in Styling Panel .........................................................................32
Figure 26: Create Calculation ......................................................................................................35
Figure 27: Reference Script Variable ...........................................................................................35
Figure 28: Edit Scripts ..................................................................................................................36
Figure 29: Multiple Events ............................................................................................................36
Figure 30: Script for Dropdown ....................................................................................................36
Figure 31: Script for Chart ............................................................................................................36
Figure 32: Hover Menu.................................................................................................................37
Figure 33: Add Script Object ........................................................................................................37
Figure 34: Add Script Function .....................................................................................................37
Figure 35: Script Object Function .................................................................................................37
Figure 36: Script of Script Object Function ..................................................................................38
Figure 37: Script Editor.................................................................................................................38
Figure 38: 3 Areas of Script Editor ...............................................................................................38
Figure 39: Accessing Objects ......................................................................................................40
Figure 40 Gross Margin per Location Chart .................................................................................65
Figure 41 Newly Added Row Has Description "Sum", ID Is a UUID ............................................68
Figure 42 Totals Member Is Generated by Choosing Show Totals .............................................69
Figure 43 Comment Row or Comment Column Is Added to Table in Frontend ..........................70
Figure 44 Input Parameter Is Not a Concrete Data Cell Selection ..............................................73
Figure 45 Time Series Chart with Forecast Enabled ...................................................................76
Figure 46 Bubble Chart with Smart Grouping Enabled ................................................................78
Figure 47 Visible Properties .........................................................................................................79
Figures 9
Therefore, analytics designer is another way to create analytical content in SAP Analytics Cloud.
An analytic application typically contains some custom logic, expressed with the help of scripts.
With analytic applications there is much more flexibility to implement custom behavior. It requires
a higher skill level to create those.
From a consumption point of view, there shouldn't be any difference between stories and analytic
applications. The consumer shouldn't be aware of whether the analytical content is a story or an
analytic application. The exposed widgets, the available functionality, and the look, feel, and
behavior should be the same.
In addition, an analytic application has a dedicated lifecycle. You start it and there are certain
steps which are performed, like the startup event, for example. The story doesn't have that. You
can switch the story between edit and view mode as often as you like.
These are major differences. That is why we offer two artifacts and two corresponding design
time environments to create stories and analytic applications.
As a first step, you need to decide whether you want to visualize your data in a table or a chart
and add a table or a chart to your analytic application. This triggers another step for picking a
model. A model is a representation of the business data of an organization, organized into
dimensions and measures. In addition to widgets showing data, you add to the layout other
widgets that control data, such as filters, arrange and configure them, and wire them up.
Almost all widgets expose events. To add custom logic to the analytic application, you can
implement event handlers with the help of the scripting language.
About Analytics Designer 13
Example:
Let's say a dropdown box is populated with the available years in the data model - 2015 to 2019.
The dropdown box exposes the event OnSelect, which is triggered whenever a value is selected
from the dropdown box. The implementation of that event handler could read the selected value
and set a filter for the selected year in the model. The numbers shown reflects the selected year.
Because you can add many event handlers using the scripting APIs of all widgets and other
service APIs offered, the application can be geared towards the specific needs of a customer.
About Analytics Designer 14
Example:
Let's say that there is an API method available for filtering members: setFilter("YEAR", "2014").
A member is an element of a dimension. The plain JavaScript method expects two strings, and
this is what is executed at runtime by the web browser. However, our definition of the API method
uses dedicated predefined types for our business domain, that is setFilter(Dimension, Member).
With that definition, the system checks and validates that the passed strings are a valid dimension
and a valid member.
The script editor uses the type information. It doesn't just statically check the types but uses the
knowledge about the underlying model and provides value help to offer dimensions and members
existing in the model.
Getting Started 15
2 Getting Started
Analytics designer provides a software development environment that enables application
designers or developers to reuse SAP Analytics Cloud widgets and other functionalities to build
different kinds of applications. Interactions between different widgets, pages, and applications are
implemented with script functionalities (including planning, machine learning, and so on) -
at design time. End users will then be consuming these applications - at runtime.
Analytics Designer is built around core story components to keep them synchronized as you go
forward. Analytics designer and Story have different entry points but share much in common:
• Analytics designer is deeply integrated into SAP Analytics Cloud.
• Analytics designer and story share data connectivity and User Interface artifacts.
• It ensures a consistent user experience for application and story consumers.
• It inherits infrastructure and lifecycle management of SAP Analytics Cloud.
2.1 Prerequisites
Full access: the application author who creates or edits the application needs a Create, Read,
Update and Delete access (CRUD). The CRUD permissions are part the standard role
Application Creator or can be assigned to any other role.
The folder where the application is stored passes on its access settings. For example, when an
application is saved in a public folder, all users get Read access by default.
The ability to create, update, and delete is part of an extra standard role Application Creator.
2.1.4 Modes
There are three modes in analytic applications:
• Edit mode
This is a design time mode. It allows you to edit applications. CRUD access is necessary.
The application opens in edit mode by default if you have CRUD access.
• Present mode
This is a runtime mode. It allows you to execute applications. Read access is necessary.
The application opens in present mode by default if you run an it from edit mode.
• View mode
This is a runtime mode. It allows you to execute applications. Read access is necessary.
The application opens in view mode by default if you have read access.
2.2.1 Canvas
The Canvas is a flexible space where you can explore and present your data. Applications have
only one canvas. Scripting allows you to build numerous navigation options in your app.
Note: Applications don’t have pages. The story concepts of cascading story, page, widget filters,
and input controls are thus unavailable in applications. You should add a Filter line widget
instead. The Filter line widget mimics the story filter and can be placed on the application canvas.
Assign a data bound source widget, such as a table or a chart, as source widget. Target widgets
can be assigned via scripting to apply the selected filters to several widgets.
Data Sources can be based on a variety of models provided by, for example:
• SAP HANA
• SAP BW
• Data Warehouse Cloud Analytical Data Set
Getting Started 17
Note: Custom widgets that are used in an analytic application are also exported with the analytic
application.
Note: The software release Wave versions of SAP Analytics Cloud installed on the source and
target tenants need to be either the same Wave version or just one Wave version different.
Save Bookmark
Write analytic designer scripts to save a bookmark. At runtime, the analytic application user can
capture the latest application state via API.
BookmarkSet_1.save("application bookmark", true, true);
Delete Bookmark
To turn on translation of an analytic application for the first time, the application developer must
open the Analytic Application Details dialog and switch on Mark for translation.
The current language will become the source language of this document. If users switch to
another language, the document will be shown only in view mode.
To export an application as a PDF, an Export to PDF component should be added when designing
an application.
Export PDF
Write analytic designer scripts to trigger the export. Then during application runtime, analytic
application users can export an application as a PDF file via the API:
ExportToPDF_1.exportView();
There are several PDF exporting settings that can be configured, such as:
• File name
• Orientation
• Paper size
• Page number location
• Date location
• Page header
• Page footer
• Insert Appendix or not
• Export comment or not
• Export in the background or not
Getting Started 20
The settings can be configured both at design time and runtime. Application designers can update
the values via the side panel of Export to PDF at design time. While at runtime, all settings can
be exposed to application users via related APIs and enable the users to configure these settings
as well.
setAppendixVisible(true);
isAppendixVisible();
setCommentsVisible(true);
isCommentsVisible();
setPageSize(PageSize.A4);
getPageSize();
setHeaderText(“Page Header”);
getHeaderText();
Getting Started 21
setHeaderVisible(true);
isHeaderVisible();
setFooterText(“Page Footer”);
getFooterText();
setFooterVisible(true);
isFooterVisible();
setPageOrientation(PageOrientation.Portrait);
getPageOrientation();
setDateLocation(PageDateLocation.Header);
getDateLocation();
setPageNumberLocation(PageNumberLocation.Header);
getPageNumberLocation();
setMetadataLocation(PageMetadataLocation.Header);
getMetadataLocation();
setExportInBackgroundEnabled(true);
isExportInBackgroundEnabled();
Manage Comment
Data cell-based comments can be managed via APIs by specifying data context or comment ID.
// Add comment to table cell
Table_1.getDataSource().getComments().addComment({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"}, "comment1");
// Remove comment by context. One data cell has only one comment
// thread. In this case, all comments belong to this thread will
// be removed.
Table_1.getDataSource().getComments().removeComments({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"});
Getting Started 22
Get Comment
Besides posting or removing comments, the application designer can read the comment
information by data context or comment ID. The comment information includes content, author,
creation date and so on.
// If comment ID is specified, the related comment is returned
var oCommentInfo2 = Table_1.getDataSource().getComments().getComment("28760729-
2540-4227-b016-428450515042");
// Get comment thread by context
var aCommentInfos =
Table_1.getDataSource().getComments().getAllComments({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"});
Be able to turn on and off comment display via APIs. Once the comment mode is disabled, the
comments and related UI will be invisible at runtime.
Application.isCommentModeEnabled();
Application.setCommentModeEnabled(true);
Like a Comment
Whether to like a comment or not can be configured via API as well. Once a comment id is
specified, the number of like of the related comment will be updated.
setCommentLiked(("28760729-2540-4227-b016-428450515042", true);
The new story will be created in a new browser page, and the settings and data state (that is,
filter, and so on) will be carried over as well.
Basically, the APIs can be used in two ways: open the analytic application or a page of a story
directly or open an URL.
The APIs take the uuid of an analytic application or a page in a story and open the expected
application or page in a new tab if parameter “newTab” is set to true.
NavigationUtils.openStory("story_uuid", "page_uuid",
[UrlParameter.create("p_script_var_1", "123"),
UrlParameter.create("p_script_var_2", "Value with Spaces")]);
NavigationUtils.openApplication("application_uuid", true);
Open URL
The user can also choose to open an URL, which is a story or analytic application URL, or even
a general external URL. The URL can be opened in a new tab or in a browser page that is already
open.
var storyURL = createStoryUrl("story_uuid", "page_uuid",
UrlParameter.create("p_script_var_1", "123"));
var appURL = createApplicationUrl("application_uuid");
openUrl(storyURL, true);
openUrl(appURL, true);
The user can also choose to open a data analyzer to analyze data of a data source. The user can
pass the name of the connection, the name of the data source, and URL parameters, if necessary.
The data analyzer opens in a new tab or in a browser page that is already open.
NavigationUtils.openDataAnalyzer("myconnection", "mydataSourceName",
UrlParameter.create("P_script_var_1", "123"), true);
Designing an Analytic Application 24
The default access set for an application saved in a public folder is read only for others. You need
to explicitly share your application with other users and give CRUD access to allow them to edit
the application.
At design time, the CRUD permissions are necessary, at runtime only read access. When users
have only read access and open an application from file repository, the application will open
automatically in runtime mode. If a user has CRUD permissions, the application will open per
default in design time mode. If you as application author with CRUD permissions want to open
the application from file repository directly in view mode, you can select this option from context
menu when hovering over the application name in the list. If you are not the owner of the
application and it was not shared with full access, the application will open in view mode and you
don’t have the option in the context menu. Only for your own applications you have this option.
In edit mode, the URL contains mode=edit. In present mode, the URL contains mode=present. In
view mode, the URL contains mode=view. In embed mode, the URL contains mode=embed. An
analytical application opened in embed mode hides the toolbar.
Designing an Analytic Application 26
The analytic application opens in present mode by default when running the application from the
design time.
• All visible widgets in the Layout area, either directly on the main Canvas or in a Popup
• The non-visible elements of an application in the Scripting area
Click on + to create Script Variables, Script Objects, OData Services, and Predictive Models. You
can maintain them here and use them in every script of the application.
The outline has a search bar that filters the complete tree to match your search. Click the symbol
> to expand or collapse an item.
The widgets in the outline, on the canvas, and the side panel are always synchronized and based
on your selection. Widgets in the outline have a context menu containing Rename, Find
Reference, Delete, and Hide. Hide conceals the widget on the canvas in edit mode. It has no
influence on the different view modes when executing the application.
Widgets have their own analytic application Properties section in the Styling panel. This is where
the widget name used for scripting can be changed; it is updated in the outline, and vice versa.
The specific properties of the analytics designer depend on the widget type.
Designing an Analytic Application 30
Dropdown Widget
Users can now configure dropdown style with greater granularity. In addition to the default style,
users can now configure different styles of dropdown menu when item are selected, or mouse
hover, or mouse down.
In addition to the default style, users can now configure different styles of filter menu during mouse
hover or mouse down.
Button Widget
Several new settings of Button widget have been added in the Styling Panel:
The possible types of button are: standard, lite, emphasized, positive (accept), and negative
(reject).
Under Actions, you can flag the option to hide the widget in application view time.
Designing an Analytic Application 32
At runtime for each widget, there are quick menus for either a widget or relevant data points (that
is, Table or Chart). An application developer can configure the visibility of these quick menu items
via the settings in the Styling Panel of a widget. More styling options are available.
By checking or unchecking the checkbox before each item, the application developer can control
the availability of the related quick menu item at runtime.
Please be advised that the configurable items in quick menus vary by widget.
Most modern analytics tools avoid scripting to simplify the designer’s tasks. Users may find it
easier to use at first, but they quickly find themselves limited to the scenarios built into the tool.
Scripting allows you to go beyond present narratives, to respond to user interaction in a custom
way, to change data result sets, and to dynamically alter layout. Scripting frees your creativity.
For example, when calling an API method on a Business Warehouse DataSource, the code
completion can propose measures as code completion options or values to specify a filter.
4.2.3 Events
Scripts always run in response to something happening in the application. Application events are
your hook. There are several types of events in analytic applications. Some occur in the
application itself and some occur on individual widgets.
Designers have access to this information and to the event’s two input parameters:
• origin: it is the domain of the host application. The contents of an iFrame don’t need to
be in the same origin as the host app, even when same origin policies are in effect. It can
be convenient but be careful about clickjacking attacks and malicious iFrame hosts. For
the sake of security, we recommend that you check this parameter to ensure that the
iFrame host is what you expect.
• message: it is the standard message parameter of the JavaScript PostMessage passed into
SAP Analytics Cloud. It does not follow any format and could be almost anything. It is
encoded using the structured clone algorithm and there are a few documented limitations
in what can and can’t be encoded.
For example, an analytic application developer can bind a calculated measure which references
one script variable (ScriptVariable_Rate) to a chart.
Scripting in Analytics Designer 35
Find them by hovering over the widget name in the outline, or as a menu entry in the quick action
menu of each widget. The icon indicates the event. By clicking on it, the script editor opens the
selected function.
If a widget has multiple available events, you are presented with a choice in the hover menu.
If there is an event with an attached script, you can see the icon in the outline pane. If there
are no attached script, there is no visible icon. In the following figure, the onSelect event of
Dropdown_1 has a script, but there are no scripts attached to Chart_1.
If a widget has multiple events and at least one has a script attached, then the icon will be
displayed.
The hover menu will show which of the events have attached scripts.
Scripting in Analytics Designer 37
Within a script object, you can add several functions, by invoking Add Script Function in the
context menu. Keep in mind that the script object container is an organizational aid for you.
Individual functions are nested within global script objects. For example, in the figure below Error! R
eference source not found. you see the function1 nested within a script object called
ScriptObject_1.
Like canvas widgets, the scripts attached to a function are created by clicking the icon in the
hover menu of that function. Functions that have and don’t have scripts are visible in the outline,
just as with widgets.
Once you have a script attached to a function, you can call it whenever you please, from any
other script. The script objects are accessible by name and individual functions are accessible
within the objects. If you wanted to invoke the function1 script within ScriptObject_1, you would
call is like this:
ScriptObject_1.function1();
Write script in the main body using the inbuild help features like code completion and value help.
Scripting in Analytics Designer 39
Find a list of keyboard shortcuts in the help page “Using Keyboard Shortcuts in the Script Editor”:
https://help.sap.com/doc/00f68c2e08b941f081002fd3691d86a7/release/en-
US/68dfa2fd057c4d13ad2772825e83b491.html.
Find all places where a widget or a scripting object is used with the Find References feature. You
can find it in the context menu per object in the outline. The result is displayed in the Reference
list tab of the Info Panel.
You can change the name of a widget, gadget, script variable, script object, or script object
function by selecting it in the Outline, clicking the More button, selecting Rename, and entering a
new name.
You can change the name of a widget or gadget by selecting it in the Outline, then entering in the
Styling Panel a new name in the Name input field.
You can change the name of a script variable, script object, or script object function by selecting
it in the Outline, entering in the Styling Panel a new name in the Name input field, then clicking
button Done.
You can change the name of a script object function argument by selecting the script object
function in the Outline, clicking the Edit button of the function argument in the Styling Panel,
entering a new name in the Name input field, then clicking button Done.
4.4.1 Typing
Normal JavaScript is weakly typed and dynamically typed. Weak typing means that the script
writer can implicitly coerce variables to act like different types. For example, you could have an
integer value and treat it as if it were a string. Dynamic typing means that the runtime will try to
guess the type from the context at that moment and the user can even change the type after the
Scripting in Analytics Designer 40
variable is already in use. For example, you could change the value of the beforementioned
integer to another type of object at will; “Dear integer, you are now a duck”.
SAP Analytics Cloud, analytics designer forbids both. Once you have a duck, it remains a duck
and you can’t recycle variable names as new types. If you want something else, you’ll need
another variable. It is also strongly typed, meaning that if you want to use an integer as a string,
you’ll have to explicitly cast it. Both are a consequence of enabling the rich code completion
capabilities in the editing environment.
The analytics designer scripting language is still JavaScript. You can write perfectly valid
JavaScript while treating the language as if it was strongly and statically typed.
Fuzzy matching helps you finding the result even if you have made a typo or the written letters
are in the middle of the function. Fuzzy matching is applied automatically for the standard code
completion (for example, "cose" → "console").
The script validation runs automatically in the background and shows errors and warnings
indicated with red and orange underlying and a red or orange marker before the line number.
All standard functions listed in the SAP Analytics Cloud, analytics designer API Reference are
supported even if some browsers don’t support them natively.
For example, String#startsWith is not available in Microsoft Internet Explorer, but can be used
in SAP Analytics Cloud with all browsers.
4.4.7 Loops
Two types of JavaScript loops are possible in SAP Analytics Cloud, analytics designer, for and
while loops. Other types, such as foreach iterators, are not supported.
SAP Analytics Cloud, analytics designer has no automatic type casting. It supports
• Triple equals
• Double equals only if both sides have the same static type
The examples below show the difference between double and triple equals operators. In both
cases, there is a variable aNumber, with an integer value and we are comparing it to the string "1".
In the double equals case, aNumber is cast to string and compared. The result is true, and the if
block is entered. In the triple equals case, aNumber is not cast to string and the comparison is
false, because the values are of a different type.
When performing the above console print on one of the events of Chart_1 itself, use the following
variation of the code:
var theDataSource = this.getDataSource();
console.log(theDataSource.getVariables());
Note: Analytics designer supports debugging analytics designer scripts in the Chrome browser
only.
Note: Analytics designer transforms the analytics designer scripts before they are run in the
browser. Thus, they will not look exactly like the script you wrote in the script editor of analytics
designer.
Note: To find the analytics designer script in the browser’s development tools, the script needs to
be run at least once during the current session.
Analytics designer script names follow a specific naming convention: All scripts of an application
are grouped in a folder <APPLICATION_NAME>. Each script is named
<WIDGET_NAME>.<FUNCTION_NAME>.js.
For example: If an application My Demo Application contains a button Button_1 with an onClick
handler, then the name of the script is Button_1.onClick.js, which is in folder
My_Demo_Application.
Note: Special characters, for example space characters in the application name are replaced by
an underscore (_), except minus (-) and dot (.) characters, which remain unchanged.
You can quickly find a script by its name with the following steps:
• Press F12 to open the browser’s development tools.
• Press CTRL+P, then start typing a part of the script’s name.
Scripting in Analytics Designer 45
You can also find a script in the file tree on the left side of the development tools using the
following steps:
• Press F12 to open the browser’s development tools.
• Select the tab Sources.
• Open the node whose name starts with sandbox.worker.main.
• Open the node named AnalyticApplication.
• Find the folder with your application’s name. The scripts that have already been executed
for the current analytic application appear in this folder.
To pause a script while it is being executed, you can set breakpoints at certain locations in the
analytic designer script.
Scripting in Analytics Designer 46
To set a breakpoint, open the script you want to pause during its execution and click on the line
number on the left side of the opened script in the developer tools.
A blue marker appears, highlighting the clicked line number. It indicates where the script will be
paused when it is being executed the next time. You can add several breakpoints in one script to
pause its execution at different points in time.
To remove a breakpoint, click on the blue marker. The blue maker disappears, and the script's
execution won't stop at this point when the script is run the next time.
Analytic designer supports more debugging features by running an analytic application in debug
mode.
You enable the debug mode for an analytic application by appending the string ;debug=true to
the URL of the analytic application in the browser.
Note: The analytic designer script names in the browser change when the analytic application is
run in debug mode. In debug mode, the suffix -dbg is added to the script name, for example,
Button_1.onClick-dbg.js.
You enable the debug mode for an analytic application by appending the string ;debug=true to
the URL of the analytic application in the browser.
Note: The analytic designer script names in the browser change when the analytic application is
run in debug mode. In debug mode, the suffix -dbg is added to the script name, for example,
Button_1.onClick-dbg.js.
When the debug mode is enabled, you can pause an analytics designer script at a specific
location while it is being executed by placing a debugger; statement at this location of the script.
The difference to a regular breakpoint is that you can define the location where the script is paused
already while writing the script itself, that is, before running it.
Scripting in Analytics Designer 47
When the debug mode is enabled, then comments in a script are preserved in the transformed
script that is executed in the browser. This makes it easier to recognize specifically commented
locations in a script when its execution in the browser is paused.
Example:
Let’s say you want to print the variables on Chart_1 to the console.
Get the data source on a widget with its getDataSource() function. This returns the data source
attached to that widget and allows you to perform further operations.
The snippet below prints the data source variables of Chart_1 to the console:
var theDataSource = Chart_1.getDataSource();
var theVariables = theDataSource.getVariables();
console.log(theVariables);
Example:
The following single filter value is set for dimension "EMPLOYEE_ID". This keeps only the member
with employee ID 230 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {value: "230"});
Example:
The following single but excluding filter value is set for dimension "EMPLOYEE_ID". This removes
the member with employee ID 230 from the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {value: "230", exclude: true});
Example:
The following multiple filter values are set for dimension "EMPLOYEE_ID". This keeps the members
with employee IDs 230 and 240 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {values: ["230", "240"]});
Example:
The following multiple but excluding filter values are set for dimension "EMPLOYEE_ID". This
removes the members with employee IDs 230 and 240 from the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {values: ["230", "240"], exclude: true});
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs between 230 and 240 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {from: "230", to: "240"});
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs less than 230 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {less: "230"});
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs less or equal than 230 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {lessOrEqual: "230"});
Scripting in Analytics Designer 49
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs greater or equal than 230 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {greaterOrEqual: "230"});
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs greater than 230 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", {greater: "230"});
You can also apply multiple range filters at once.
Example:
The following range filter applied to dimension "EMPLOYEE_ID" keeps the members with employee
IDs less than 230 and greater than 240 in the drill-down:
DS_1.setDimensionFilter("EMPLOYEE_ID", [{less: "230"}, {greater: "240"}]);
Example:
In the following example, the dimension filter values of the filter COUNTRY are retrieved:
var values = Table_1.getDataSource().getDimensionFilters("COUNTRY");
Each value in the array is an instance of either SingleFilterValue, MultipleFilterValue, or
RangeFilterValue, which all inherit from FilterValue. To work with such an instance, that is, to
access its type-specific properties, cast the instance to the corresponding type first, using the
type property. The following example shows how:
var value = Table_1.getDataSource().getDimensionFilters("COUNTRY")[0];
switch (value.type) {
case FilterValueType.Single:
var singleValue = cast(Type.SingleFilterValue, value);
console.log(singleValue.value); // you can access the 'value' property now
break;
case FilterValueType.Multiple:
var multipleValue = cast(Type.MultipleFilterValue, value);
console.log(multipleValue.values); // you can access the 'values' property now
break;
case FilterValueType.Range:
var rangeValue = cast(Type.RangeFilterValue, value);
console.log(rangeValue.from); // you can access the 'from' property now
console.log(rangeValue.to); // you can access the 'to' property now
// further range properties: 'less', 'lessOrEqual', 'greater', 'greaterOrEqual'
break;
default:
Scripting in Analytics Designer 50
break;
}
Note: Currently this API does not return time range filters.
Note: In SAP BW backend systems you can create valid filters that are not yet supported by SAP
Analytics Cloud. As this API implementation is based on SAP Analytics Cloud, it supports the
capabilities of SAP Analytics Cloud.
getDimensionProperties
getDimensionProperties(dimension: string | DimensionInfo): DimensionPropertyInfo[]
Returns all available dimension properties of the specified dimension of a data source.
4.5.4 Hierarchies
You can set the drill level of a dimension hierarchy as well as expand or collapse individual
hierarchy nodes.
Note: Currently, this is supported only by data sources of Table and Chart widgets.
Specify the dimension and hierarchy level that you would like to set or retrieve:
DataSource.setHierarchyLevel(dimension: string|DimensionInfo, level?: integer):
void
DataSource.getHierarchyLevel(dimension: string|DimensionInfo): integer
Specify the dimension and hierarchy node that you would like to expand or collapse:
DataSource.expandNode(dimension: string|DimensionInfo, selection: Selection): void
DataSource.collapseNode(dimension: string|DimensionInfo, selection: Selection):
void
Chart_1.getDataSource().expandNode("Location_4nm2e04531", {
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]", // California
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Discount]"
});
Suppose you were only logging the variables in the above example as a debug aid. You were not
re-using them, and the multiple lines were visual clutter. Then you might want to use method
chaining. The code below uses method chaining for compactness and does the same thing:
console.log(Chart_1.getDataSource().getVariables());
• Importing scripts
• Including ActiveX, and so on
• Launching other Web Workers
• Accessing cookies
• Enforcing different domains
Validation
Validation at runtime follows the same logic as for the script editor. Not all validations have to be
performed, for example, validating analytic data like filter values.
The JavaScript environment runs in the normal browser space along with the rest of the widget
scripts.
Execution Order
On Startup, the R script runs and the JavaScript onResultSetChanged doesn’t run because the
widget is in its initial view state.
On data change, the R script runs first, the JavaScript onResultChanged event runs.
The R environment can be accessed from the JavaScript environment. It can be read from and
manipulated. However, the JavaScript environment can’t be accessed from the R environment.
Reading
Suppose you had an R widget that had a very simple script. It just gets the correlation coefficient
between two measures on a model and puts that into a number named gmCorrelation:
grossMargin <- BestRun_Advanced$`Gross Margin`
grossMarginPlan <- BestRun_Advanced$`Gross Margin Plan`
gmCorrelation <- cor(grossMargin, grossMarginPlan)
Use the getEnvironmentValues on the R widget to access its environment and getNumber to read
a number from the R environment. The following JavaScript code takes the correlation coefficient
from the R environment and logs it to the JavaScript console. Note the this. This code was taken
from the onResultChanged event of a widget with the above R snippet. It means that R widgets
can be used as global data science scripts:
var nCcor = this.getEnvironmentValues().getNumber("gmCorrelation");
var sCor = nCcor.toString();
console.log("Margin Correlation: " + sCor);
Scripting in Analytics Designer 53
Writing
You can also manipulate the R environment from JavaScript. The magic methods are
getInputParameters and setNumber. The following line of JavaScript sets an R environment
variable named userSelection to 0.
RVisualization_1.getInputParameters().setNumber("userSelection", 0);
Lumira scripts execute on the server. SAP Analytics Cloud, analytics designer scripts execute in
the browser JavaScript engine. Lumira scripts execute close to the data. SAP Analytics Cloud,
analytics designer scripts execute close to the user.
SAP Analytics Cloud, analytics designer is not copy-and-paste compatible with Lumira. This is
partially a consequence of the close-to-data vs close-to-user philosophical difference.
Data sources are currently hidden within data bound widgets and you must access them using
getDataSource(). When standalone data sources become available, you will be able to access
them as global variables, as in Lumira.
SAC Analytics Designer not supporting automatic type conversion makes scripts more explicit
and avoids common mistakes. This includes requiring a strict equality comparison operator,
whereas Lumira allowed the use of the double equals comparison operator for expressions of
different types.
Widget Concepts, APIs, and Usages 54
Once you have added a widget to the canvas, you can then use its Builder Panel, Styling Panel,
and Action Menu to configure its styling and runtime behavior, and even write script to configure
how it interacts with other widgets.
If you need more information about any script API in analytics designer, you can read through the
API Reference document which you can open from the help portal:
https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/latest/en-US/index.html
This is very useful, for example, if you need a specific user interface element, a particular
visualization of data, or a certain functionality in your analytic application that is not provided by
the predefined set of widgets.
Custom widgets seamlessly integrate into SAP Analytics Cloud, analytics designer.
https://help.sap.com/viewer/0ac8c6754ff84605a4372468d002f2bf/latest/en-US.
The action menu is a dynamic menu and is only visible if the widget is selected. Different
widgets have different options available, and some of the options are not available in view mode.
5.6 Table
Analytics designer provides Table APIs and Data Source APIs to help analytics designers use
script custom specific logic into their analytic applications.
Besides the common widget APIs like getVisible() and setVisible(), the main Table APIs are
listed below:
addDimensionToColumns
addDimensionToColumns(dimension: string|Dimension, position?: integer): void
Adds the dimension to the column axis at the specified position. If no position is specified, the
dimension is added as the last dimension of the column axis.
Example:
Table_1.addDimensionToColumns("Location_4nm2e04531");
addDimensionToRows
addDimensionToRows(dimension: string|Dimension, position?: integer): void
Adds the dimension to the row axis at the specified position. If no position is specified, the
dimension is added as the last dimension of the row axis.
Example:
Table_1.addDimensionToRows("Location_4nm2e04531");
getDataSource
getDataSource(): DataSource
Returns the data source of the table. If the table has no data source, undefined is returned. Refer
to the section on data related APIs.
getDimensionsOnColumns
getDimensionsOnColumns(): Dimension[]
Returns the dimensions on the column axis.
getDimensionsOnRows
getDimensionsOnRows(): Dimension[]
Returns the dimensions on the row axis.
getPlanning
getPlanning(): Planning
Returns the planning object of the table. If the table data source is not of type planning, undefined
is returned.
getSelections
getSelections(): Selection[]
Returns the selections of the chart. You can use the elements of the returned array with the
function DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html).
Widget Concepts, APIs, and Usages 59
getSelections(): Selection[]
Returns the selections of the chart. You can use the elements of the returned array with the
function DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html).
removeDimension
removeDimension(dimension: string|Dimension): void
Removes the dimension from whichever axis it is present on. If the dimension is neither on the
Rows nor Columns axis, the operation is ignored.
Example:
Table_1.removeDimension("Location_4nm2e04531");
openNavigationPanel
openNavigationPanel(navigationPanelOptions?: NavigationPanelOptions): void
Opens the navigation panel of the table. Open the navigation panel in its expanded state by
specifying this in the navigation panels options:
Example:
Table_1.openNavigationPanel({expanded: true});
closeNavigationPanel
closeNavigationPanel(): void
Closes the navigation panel of the table.
Example:
Table_1.closeNavigationPanel();
Note: This API is available on Table widgets and is applicable to SAP BW models only.
setCompactDisplayEnabled
setCompactDisplayEnabled(axis: TableAxis, enabled: boolean)
Enables or disables the compact display (formerly called Universal Display Hierarchy) on the
specified table rows or columns axis.
isCompactDisplayEnabled
isCompactDisplayEnabled(axis: TableAxis): boolean
Returns whether compact display (formerly called Universal Display Hierarchy) is enabled on the
specified table row or column axis.
Widget Concepts, APIs, and Usages 60
Note: This API is available on Table widgets and is applicable to SAP BW models only.
setZeroSuppression
setZeroSuppression(axis: TableAxis, enabled: boolean)
Enables or disables zero suppression on the specified table rows or column axis.
isZeroSuppressionEnabled
isZeroSuppressionEnabled(axis: TableAxis): boolean
Returns whether zero suppression is enabled on the specified table rows or columns axis.
setActiveDimensionProperties
setActiveDimensionProperties(dimension: string | DimensionInfo, properties:
string[] | DimensionPropertyInfo[])
Sets the active (visible) dimension properties of the specified dimension.
getActiveDimensionProperties
getActiveDimensionProperties(dimension: string | DimensionInfo): string[]
Returns the IDs of the currently active (visible) dimension properties of the specified dimension.
onResultChanged
onResultChanged()
Called when the result set displayed by the table changes.
onSelect()
onSelect()
Called when the user selects within the table.
NumberFormatScaleUnit.Default;
NumberFormatScaleUnit.Unformatted;
NumberFormatScaleUnit.AutoFormatted;
NumberFormatScaleUnit.Thousand;
NumberFormatScaleUnit.Million;
NumberFormatScaleUnit.Billion;
NumberFormatScaleUnit.Default;
NumberFormatScaleFormat.Long;
NumberFormatScaleFormat.Short;
NumberFormatScaleFormat.Default;
NumberFormatDisplayUnit.Default;
NumberFormatDisplayUnit.Row;
NumberFormatDisplayUnit.Column;
NumberFormatDisplayUnit.Cells;
NumberFormatSignDisplay.Default;
NumberFormatSignDisplay.MinusAsParentheses;
NumberFormatSignDisplay.MinusAsPrefix;
NumberFormatSignDisplay.PlusMinusAsPrefix;
5.7 Chart
Besides the common widget APIs like getVisible() and setVisible(), the main Chart APIs are
as below:
addDimension
addDimension(dimension: string|Dimension, feed: Feed, position?: integer): void
Adds a dimension to the feed at the specified position. If no position is specified, the dimension
is added at the end of the feed.
Example:
Chart_1.addDimension("Location_4nm2e04531", Feed.CategoryAxis);
addMeasure
addMeasure(measure: string|Measure, feed: Feed, position?: integer): void
Widget Concepts, APIs, and Usages 62
Adds the measure to the feed, at the specified position. If no position is specified, the measure is
added at the end of the feed.
Example:
Chart_1.addMeasure("[Account_BestRunJ_sold].[parentId].&[Gross_MarginPlan]",Feed.Va
lueAxis);
getDataSource
getDataSource(): DataSource
Returns the data source of the chart. If the chart has no data source, undefined is returned.
getForecast
getForecast(): Forecast
Returns the forecast of the chart.
getMeasure
getMeasures(feed: Feed): Measure[]
Returns the measures of the feed.
Example:
var measures = Chart_1.getMeasures(Feed.ValueAxis);
getSelections
getSelections(): Selection[]
Returns the selections of the chart. You can use elements of the returned array with the function
DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html).
getSmartGrouping
getSmartGrouping(): SmartGrouping
Returns the Smart Grouping of the chart.
removeDimension
removeDimension(dimension: string|Dimension, feed: Feed): void
Removes the dimension from the feed.
Example:
Chart_1.removeDimension("Location_4nm2e04531", Feed.CategoryAxis);
removeMeasure
removeMeasure(measure: string|Measure, feed: Feed): void
Removes the measure from the feed.
Widget Concepts, APIs, and Usages 63
Example:
Chart_1.removeMeasure("[Account_BestRunJ_sold].[parentId].&[Gross_MarginPlan]",Feed
.ValueAxis);
onResultChanged
onResultChanged()
Called when the result set displayed by the chart changes.
onSelect
onSelect()
Called when the user selects within the chart.
NumberFormatScaleUnit.Default;
NumberFormatScaleUnit.Unformatted;
NumberFormatScaleUnit.AutoFormatted;
NumberFormatScaleUnit.Thousand;
NumberFormatScaleUnit.Million;
NumberFormatScaleUnit.Billion;
NumberFormatScaleUnit.Default;
NumberFormatScaleFormat.Long;
NumberFormatScaleFormat.Short;
NumberFormatScaleFormat.Default;
NumberFormatSignDisplay.Default;
NumberFormatSignDisplay.MinusAsParentheses;
NumberFormatSignDisplay.MinusAsPrefix;
NumberFormatSignDisplay.PlusMinusAsPrefix;
Widget Concepts, APIs, and Usages 64
Before these APIs had been introduced, you could retrieve individual data cells using
DataSource.getData(). However, it was not possible to retrieve all members for a dimension in a
specific result set.
Note: To reference in a selection the NULL member, use the alias Alias.NullMember.
Note: To reference in a selection the totals member, use the alias Alias.TotalsMember.
To help you understand using this API, we list several examples. As ID of dimension and measure
is used in input parameter and returned by the result set, we choose to display both ID and
description for tables and charts in these examples.
Function Summary:
// Returns the result set according to the selected data or context of
// the data you select. Offset/limit should be not less than zero. If
// offset/limit are invalid or not set, all data is returned.
// If the selection does not specify any MeasureDimension, all measures
// are returned.
Chart_1.getDataSource().getResultSet(selection?: Selection | Selection[] |
SelectionContext, offset?: integer, limit?: integer): ResultSet[]
Table_1.getDataSource().getResultSet(selection?: Selection | Selection[] |
SelectionContext, offset?: integer, limit?: integer): ResultSet[]
ResultSet {
[key: string]: DataContext;
}
Selection {
[key: string]: string;
}
SelectionContext {
Widget Concepts, APIs, and Usages 65
DataContext {
id: string
description: string
formattedValue: string
rawValue: string
parentId: string
}
Here is an example that shows the result when no input parameter is specified: All data points of
Chart_1 are returned. Dimension context includes parent information if it has a hierarchy structure.
Measure context includes formattedValue and rawValue.
The below chart shows Gross Margin per Location. Include Parent Levels has been checked in
the Builder Panel.
Chart_1.getDataSource().getResultSet();
// ResultSet[].
// Both CT1 and CT2 have parentId "SA1". The result set is partially listed.
[{
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"formattedValue": "173.48",
Widget Concepts, APIs, and Usages 66
"rawValue": "173481592.97"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"description": "California"
}
}, {
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"formattedValue": "48.97",
"rawValue": "48971999.74"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"description": "Los Angeles",
"parentId": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]" // CT1's
parentId is "SA1"
}
}, {
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"formattedValue": "19.62",
"rawValue": "19619690.4"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT2]",
"description": "San Francisco",
"parentId": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]" // CT2's
parentId is "SA1"
}
}, {
...
}]
Example 2: Get a result set when a data point in a chart has more than one measure
If a chart has more than one measure, such as a bubble or scatter chart, each measure combined
with its dimension context represents a cell in the ResultSet array. For example, one data point
of a bubble chart has three cells in the ResultSet array. They represent Gross Margin Per
Location, Profit Per Location, and Original Sales Price Per Location, respectively.
Chart_1.getDataSource().getResultSet();
// ResultSet[].
// Three cells of ResultSet array represent one data point of a bubble chart.
[{
"@MeasureDimension": { // Gross_Margin on X axis
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
Widget Concepts, APIs, and Usages 67
"formattedValue": "48.97",
"rawValue": "48971999.74"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"description": "California"
}
}, {
"@MeasureDimension": { // Profit on Y axis
"id": "[Account_BestRunJ_sold].[parentId].&[Profit]",
"description": "Profit",
"formattedValue": "19.62",
"rawValue": "19619690.4"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"description": "California"
}
}, {
"@MeasureDimension": { // Original_Sales_Price as bubble size
"id": "[Account_BestRunJ_sold].[parentId].&[Original_Sales_Price]",
"description": "Original Sales Price",
"formattedValue": "0.82",
"rawValue": "819975.23"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"description": "California"
}
}, {
...
}]
At both design time and runtime, additional columns can be added to the table by right-clicking a
table cell and adding a calculation. As these generated columns are part of the table, they are
also returned in the result set.
Widget Concepts, APIs, and Usages 68
Example 3: Newly added row has the description “Sum” and its ID is a UUID
Table_1.getDataSource().getResultSet();
}]
Table_1.getDataSource().getResultSet();
In the below example, a comment column is added to a table and one comment cell is input with
text.
Widget Concepts, APIs, and Usages 70
Table_1.getDataSource().getResultSet();
// ResultSet[]
[{
"Version": {
"id": "public.Actual",
"description": " Actual"
},
"@MeasureDimension": {
"id": "[Account].[parentId].&[TOTAL]",
"description": "TOTAL",
"rawValue": "61254901.96",
"formattedValue": "61,254,901.96"
}
}, {
"Version": {
"id": "24769565-5194-4582-9346-349222998310",
"description": " Comment"
},
"@MeasureDimension": {
"id": "[Account].[parentId].&[TOTAL]",
"description": "TOTAL",
"rawValue": "comment test",
"formattedValue": "comment test"
}
}, {
Widget Concepts, APIs, and Usages 71
...
}]
The table row can be hidden, removed, or excluded. In these cases, only visible rows are returned
by the getResultSet API.
If there are many rows in one table and a scroll bar is displayed, even though some of the rows
are temporarily invisible, getResultSet API still returns all data cells in this table because all data
are already fetched and sent to the frontend.
Users can specify a concrete selection of a data cell to get its description, parentId,
formattedValue, and rawValue.
Example 7: Specify Selection parameter, location dimension member equals CT1 or CT2
The Selection parameter can be an array and multiple filters are supported. The below condition
describes that the location dimension member should equal CT1 or CT2.
// Input parameter is Selection[]
Chart_1.getDataSource().getResultSet([{
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]"
}, {
Widget Concepts, APIs, and Usages 72
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT2]"
}]);
We also introduce the SelectionContext as a parameter. As measure is the same (Gross Margin)
in this case, the measure ID is specified only once. The below example has the same result set
as the previous one.
Chart_1.getDataSource().getResultSet({
"@MeasureDimension": ["[Account_BestRunJ_sold].[parentId].&[Gross_Margin]"],
"Location_4nm2e04531":
["[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT2]"]
});
Example 9: Selection specified by input parameter is not targeted to a certain data cell
If the input parameter is not a concrete data cell selection, all data cells matching this condition
are returned.
Widget Concepts, APIs, and Usages 73
Table_1.getDataSource().getResultSet({
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]"
});
// ResultSet[].
// Five data cells are returned as one data cell is selected by two selection.
[{
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "25388481.78",
"formattedValue" "25.39"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"description": "California"
},
"Product_3e315003an": {
"id": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]",
"description": "Alcohol"
}
}, {
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Discount]",
"description": "Discount",
"rawValue": "3765388.14",
"formattedValue" "3.77"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA2]",
"description": "Nevada"
},
"Product_3e315003an": {
"id": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC1]",
Widget Concepts, APIs, and Usages 75
Example 11: How to define and use parameter offset and limit
Parameter offset and limit are used to limit the amount of data cells.
Offset skips the offset cells before beginning to return the cells.
The data point context of the actual date has the measure actualValue. If there is fitted line in this
date, another measure hindcastValue can be found.
The data point context of the forecast date has three measures: upperBound, lowerBound, and
forecastValue.
Example 12: Time Series chart with forecast enabled, extra data point is generated
The Time Series chart below has both an actual date and a forecast date. The blue area is
generated by the forecast.
Chart_1.getDataSource().getResultSet();
// ResultSet[]
[{
"Date_703i1904sd.CALMONTH": {
"id": "201409",
"description": "Sep 2014" // actual date
},
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "4207974.43",
"formattedValue": "4207974.43"
Widget Concepts, APIs, and Usages 77
},
"@Forecast": {
"id": "actualValue"
}
}, {
"Date_703i1904sd.CALMONTH": {
"id": "201409",
"description": "Sep 2014" // actual date
},
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "5903071.626874865",
"formattedValue": "5903071.626874865"
},
"@Forecast": {
"id": "hindcastValue" // fitted line in dashed line
}
},
...
{
"Date_703i1904sd.CALMONTH": {
"id": "1498867200000",
"description": "Jul 2017" // forecast date
},
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "7115040.662185087",
"formattedValue": "7115040.662185087"
},
"@Forecast": {
"id": "forecastValue"
}
}, {
"Date_703i1904sd.CALMONTH": {
"id": "1498867200000",
"description": "Jul 2017" // forecast date
},
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "10076952.088587102",
"formattedValue": "10076952.088587102"
},
"@Forecast": {
"id": "upperBound"
}
}, {
Widget Concepts, APIs, and Usages 78
"Date_703i1904sd.CALMONTH": {
"id": "1498867200000",
"description": "Jul 2017" // forecast date
},
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"rawValue": "4153129.2357830727",
"formattedValue": "4153129.2357830727"
},
"@Forecast": {
"id": "lowerBound"
}
}]
Example 13: Bubble chart with smart grouping enabled, extra measure is generated
If smart grouping is enabled in a bubble chart, it generates one extra measure to identify the group
of each data point.
Chart_1.getDataSource().getResultSet();
// ResultSet[]
[{
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Discount]",
"description": "Discount",
"formattedValue": "1184733.37",
Widget Concepts, APIs, and Usages 79
"rawValue": "1184733.37"
},
"Store_3z2g5g06m4": {
"id": "ST1",
"description": "Second Hand"
},
"Smart Group": {
"id": "Predictive Clustering Group 1", // this data cell is in group 1
"description": "Group1"
}
},
...
{
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Discount]",
"description": "Discount",
"formattedValue": "1969249.25",
"rawValue": "1969249.25"
},
"Store_3z2g5g06m4": {
"id": "ST38",
"description": "Henrys Corner Store"
},
"Smart Group": {
"id": "Predictive Clustering Group 2", // this data cell is in group 2
"description": "Group 2"
}
}, {
...
}]
The method getResultSet() returns an array of ResultSet objects. Each ResultSet is an object
of DataContext objects. A DataContext object can contain the property properties that contains
the visible properties. Or more formally:
Table_1.getDataSource().getResultSet(selection?: Selection | Selection[] |
SelectionContext, offset?: integer, limit?: integer): ResultSet[]
Function Summary
// Returns the selection of data cells
// Offset/limit should be not less than zero.
// If offset/limit is invalid or not set, all data is returned.
// If the selection doesn't specify any MeasureDimension, all measures
// are returned.
Chart_1.getDataSource().getDataSelections(selection?: Selection | Selection[] |
SelectionContext, offset?: integer, limit?: integer): Selection[]
Table_1.getDataSource().getDataSelections(selection?: Selection | Selection[] |
SelectionContext, offset?: integer, limit?: integer): Selection[]
Let’s use the previous chart from example 1 with Gross Margin per Location.
// Selection[]
[{
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]"
}, {
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC1]"
Widget Concepts, APIs, and Usages 81
}, {
...
}]
Let’s use the previous example 9 Gross Margin per Location and Product.
// Selection[]
[{
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]"
}, {
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC1]"
}, {
...
}]
Function Summary
// Get member metadata, works for data cell and header cell
Chart_1.getDataSource().getResultMember(dimension: String | DimensionInfo,
selection: Selection): ResultMemberInfo | undefined
Table_1.getDataSource().getResultMember(dimension: String | DimensionInfo,
selection: Selection): ResultMemberInfo | undefined
ResultMemberInfo {
id: string
description: string
parentId: string
}
Widget Concepts, APIs, and Usages 82
Table_1.getDataSource().getResultMember("Location_4nm2e04531", {
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"Product_3e315003an":
"[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]",
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]"
});
// ResultMember
{
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT1]",
"description": "Los Angeles",
"parentId": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]"
}
The below example identifies a header member instead of a single data cell.
Table_1.getDataSource().getResultMember("Location_4nm2e04531", {
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]"
});
// ResultMember
{
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"description": "California"
}
Widget Concepts, APIs, and Usages 83
Example 18: Return undefined if more than one result set member found
If the input parameter can't identify a single result member, for example, both California and Los
Angeles have an Alcohol product, this API returns undefined.
Table_1.getDataSource().getResultMember("Location_4nm2e04531", {
"Product_3e315003an": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]"
});
// ResultMember
undefined
If the same logic is applied to the table below, California is returned, as there is only one location
in that table.
Figure 49 Return "undefined" If More Than One Result Set Member Found
The method getResultMember() returns an ResultMemberInfo object. It can contain the property
properties that contains the visible properties. Or more formally:
Table_1.getDataSource().getResultMember(dimension: String | DimensionInfo,
selection: Selection) : ResultMemberInfo
Note: Even if there are some widgets, for example charts created based on the same data source,
refreshing one chart won’t cause the other charts to refresh automatically.
Write the script for the onInitialization() event of the canvas to refresh Chart_1 and Table_1
when initializing an application:
var ds1 = Chart_1.getDataSource();
var ds2 = Table_1.getDataSource();
Application.refreshData([ds1, ds2]);
Use the Refresh Data API together with the Timer API to refresh a widget periodically:
// Write the script for the onTimeout event of Timer_1
// to refresh data of Chart_1 and Chart_2 every one minute.
Chart_1.getDataSource().refreshData();
Widget Concepts, APIs, and Usages 85
Chart_2.getDataSource().refreshData();
Timer_1.start(60);
Example:
In the following example, the Prompt dialog of a table’s data source is opened:
Table_1.getDataSource().openPromptDialog();
Example:
In the following example, the names of all variables of a data source are printed to the browser
console:
var aVariables = Table_1.getDataSource().getVariables();
for (var i = 0; i < aVariables.length; i++) {
console.log(aVariables[i].id);
}
Note: By default, this function will apply variable values of a variable to the model used by the
data source of the application. The widget can be configured such that variables are applied to
the model of the widget only (see Figure 51). You can find out, for example, in the title area of the
table whether the variables are applied on the model of the data source of the application (grey
braces) or on the model of the widget only (blue braces) (see Figure 52).
Widget Concepts, APIs, and Usages 86
Figure 51: Prompt Dialog: Variable Values Are Applied to the Widget Only
Figure 52: Variable Values Are Applied to the Model of the Application or the Widget
Note: This method is not validating the specified variable values neither at runtime nor at design
time. All values and value combinations which are accepted in the Prompt dialog will be
supported. All other combinations might lead to errors or inconsistent state.
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {value: "5"});
or, alternatively,
Table_1.getDataSource().setVariableValue("VAR_NAME", "5");
If the variable supports excluding a single variable value, you can set the variable value as follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {exclude: true, value: "5"});
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {values: ["5", "7"]});
Widget Concepts, APIs, and Usages 87
If the variable supports excluding multiple values, you can set the variable value as follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {exclude: true, values: ["5",
"7"]});
5.10.3.3 Comparisons
If the variable supports comparison operations <, <=, >, and >= you can set the variable value as
follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {less: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {lessOrEqual: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {greater: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {greaterOrEqual: "5"});
5.10.3.4 Ranges
If the variable supports a range of variable values, you can set the variable value as follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {from: "5", to: "7"});
If the variable supports excluding a range of variable values, you can set the variable value as
follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {exclude: true, from: "5", to:
"7"});
Example:
In the following example, the variable values of the variable V_Country are retrieved:
var values = Table_1.getDataSource().getVariableValues("V_Country");
Each value in the array is an instance of either SingleVariableValue, MultipleVariableValue, or
RangeVariableValue, which all inherit from VariableValue. To work with such an instance, that is,
to access its type-specific properties, cast the instance to the corresponding type first, using the
type property. The following example shows how:
var value = Table_1.getDataSource().getVariableValues("V_Country")[0];
switch (value.type) {
case VariableValueType.Single:
var singleValue = cast(Type.SingleVariableValue, value);
console.log(singleValue.value); // you can access the 'value' property now
break;
case VariableValueType.Multiple:
Widget Concepts, APIs, and Usages 88
Example:
If you have several options to set multiple values, then the following lines are equivalent:
Table_1.getDataSource().setVariableValue("V_Country", {values: ["DE", "FR"],
exclude: true});
Table_1.getDataSource().setVariableValue("V_Country", [{value: "DE", exclude:
true}, {value: "FR", exclude: true}]);
getVariableValues() always returns as few VariableValue objects as possible, grouping all
single values with the same sign, that is including or excluding, into one values object. In the
example, an array with only one object is returned:
[{values: ["DE", "FR"], exclude: true}]
In SAP BW models you can define variables that correspond to user-modifiable settings like filters
or hierarchies. For example, setting a variable value sets the exact same value as the filter on the
related dimension.
Note: Synchronization in the other direction is not performed by getVariableValues(). Thus, the
getVariableValues() still returns the same variable value, even though the user might have
modified the filter in the meantime. To retrieve the current value of such special variables, use
getDimensionFilters() instead. For hierarchy variables use getHierarchy().
Note: If you remove a variable value from a mandatory variable, then this operation is ignored.
Example:
Note: If you copy an empty variable value to a mandatory variable then copying this variable value
is ignored.
Note: If you copy a variable value to a data source of a widget that overrides variables and the
variable is of type text, then copying this variable value is ignored.
Example:
In the following example, the variable value of variable V_Country is copied from data source 1 to
data source 2:
var DS_1 = Table_1.getDataSource();
Table_2.getDataSource().copyVariableValueFrom(DS_1, "V_Country");
Example:
In the following example, the variable values of variables V_Country and V_Supervisor are copied
from data source 1 to data source 2:
var DS_1 = Table_1.getDataSource();
Table_2.getDataSource().copyVariableValueFrom(DS_1, ["V_Country", "V_Supervisor"]);
Example:
In the following example, the variable values of all variables are copied from data source 1 to data
source 2:
var DS_1 = Table_1.getDataSource();
Table_2.getDataSource().copyVariableValueFrom(DS_1);
For instance, a Popup can show a description of the application, and another Popup can ask the
user to perform configurations. Because the popup acts as a container widget, you can put any
other widget into the popup, such as a table, button, or checkbox.
You can choose to design a popup starting from scratch. Start with an empty canvas and have
the flexibility to add whatever widget you want. You can enable the header and footer setting to
turn the popup directly into a popup dialog that has a consistent look and feel compared to other
dialogs in SAP Analytics Cloud stories.
close
close(): void
Widget Concepts, APIs, and Usages 90
getTitle
open
setTitle
isButtonEnabled
isButtonEnabled(buttonId: string): Boolean
Returns whether the specified button in the footer of the popup is enabled.
isButtonVisible
isButtonVisible(buttonId: string): Boolean
Returns whether the specified button in the footer of the popup is visible.
setButtonEnabled
setButtonEnabled(buttonId: string, enabled: boolean): void
Enables or disables the specified button in the footer of the popup.
setButtonVisible
setButtonVisible(buttonId: string, visible: boolean): void
Shows or hides the specified button in the footer of the popup.
onButtonClick
onButtonClick(buttonId: string)
Called when the user clicks one of the buttons in the footer of the popup.
onButtonClick
onButtonClick(buttonId: string)
Called when the user clicks one of the buttons in the footer of the popup.
Widget Concepts, APIs, and Usages 91
Need to add at least two widgets to a popup to run the popup as designed
We recommend you add at least two widgets to a popup as widgets are the visualization of the
popup. If no widgets are added, you won't see the popup displayed when you trigger it while
running the analytic application. If only one widget is added, the height and width you set for the
popup won't take effect.
When a table or chart in the canvas act as the source widget of a filter line widget in a
popup, source widget can’t find the filter line as its reference after reloading the analytic
application
In the case when a table or chart in the canvas act as the source widget of a filter line widget in a
popup and you reopen or refresh the analytic application, you will find the filter line isn’t listed in
the reference list of the table or chart widget after you choose Find Reference. This is because
currently we don't initiate the filter line widget in the popup when you first entering an analytic
application.
To solve this, for now we recommend you activate the popups by clicking on each of them. Then
the reference list will display all relevant results.
The text style can be configured by each segment. In-place edit the text by double-clicking the
Text input field of Text_Title in Canvas and config the style of description.
The script variable can be exposed as URL parameter if you switch on the option. For example,
if you input p_ScriptVariable_Currency=CNY in the URL link, you’ll get the following:
Configure Feeds
The RSS feeds in the widget can be updated dynamically at runtime via APIs when you select in
Chart_RSSCategory in Present relevant RSS articles.
Example:
If you select Business in the chart, BBC Business is added in the list of feeds and selected by
default after running the scripts below:
RssReader_Content.removeAllFeeds();
RssReader_Content.addFeed("BBCBusiness","http://feeds.bbci.co.uk/news/business/rss.
xml");
RssReader_Content.setSelectedFeed("http://feeds.bbci.co.uk/news/business/rss.xml")
5.14 R Visualization
Use the R Visualization widget to leverage R scripts. It allows you to build your own visualizations,
do calculation, and more. Refer to sample Show R Visualization result in Text for the most
frequently used APIs.
In the script of R Visualization, you can define parameters to get input values or return results
calculated in the script.
Example:
Configure the title of visualization R Visualization in Show R Visualization result in Text per
location by input parameter:
RVisualization.getInputParameters().setString("titleParam", "Gross Margin of
Oregon");
Example:
Calculate the total of gross margin in RVisualization script, and return the result:
RVisualization.getEnvironmentValues().getNumber("totalSum");
Configure the data source of the R Visualization via APIs. For example, in Show R Visualization
result in Text, the dimension filter is set to Oregon when you change location via
Dropdown_Location by this
RVisualization.getDataFrame("BestRunJuice_SampleModel").getDataSource().setDimensio
nFilter("Location_4nm2e04531", ["CT13", "CT14", "CT15", "CT16", "CT17", "CT18"]);
Widget Concepts, APIs, and Usages 93
The Geo Map widget in an analytic applications has the same capabilities as in a Story, and also
provides APIs to make changes by scripting.
Since a Geo Map widget can have multiple visualization layers on the top, there are APIs to
control their visibility so users can decide which layers they need to see.
GeoMap_1.getLayer(0).setVisible(true);
GeoMap_1.getLayer(0).isVisible();
5.16 Timer
The Timer widget enables you to start a timer to trigger timing events. By leveraging the feature
of a timer, you can realize different scenarios such as:
• Create animations
• Send notifications to end users regularly
• Refresh your analytic application in a certain interval of time
To further delve into its usage, I will share two samples for your reference.
In this sample, we add animation to the header above, making the tiles (widgets) shift from right
to left repeatedly.
In order to make a TabStrip widget look like a page book, a small tip is to hide the header of the
Tabstrip, for example, using a shape, then use API TabStrip_1.setSelectedKey(TabID) to
dynamically “slide” the tab.
o Name
• Size and Position
• Widget
o Background Color
o Border
• Actions
o Show at view time or not
o Order
• List Box Style
o Selected
o Mouse Hover
o Mouse Down
• Font
5.17.4 Events
The onSelect event is triggered when the end user makes a selection at runtime.
getLayout(): Layout
// Selects an item in the List Box. The item is specified by its key.
setSelectedKey(key: string): void
// Selects items in the List Box. The items are specified by their keys.
// If the List Box is single selection, the first item of the specified keys
// will be selected.
setSelectedKeys(key: string[]): void
// Removes an item from the List Box. The item is specified by its key.
removeItem(key: string): void
We don’t have the mechanism yet to automatically flow the widgets when the screen size changes,
which will be introduced in future. But we can cover some of the responsive scenarios by
combining dynamic layout and the scripting APIs. In an analytic application, more than just flow
UI, you have the flexibility to add a widget on top of a background shape, overlapping but not flow
them, and they can shrink or grow in the same proportion when the window size changes.
You can set each widget's Left, Width, Right and Top, Height, Bottom values in Pixel, Percentage
and Auto (relative to its parent container, root canvas if not in a container) values on the Styling
panel's Layout Section.
In order to adapt to the screen real-estate at runtime on different machines or browser window,
you need to set the unit to percentage (%) or auto.
Application canvas onResize event, the event is cached to be dispatch every 500 ms when the
application window resizes.
Inside the onResize event, you can use the Layout API to dynamically set the size and position.
Widget Concepts, APIs, and Usages 101
Below code sample shows how to adjust the layout to fit a small screen size like phone.
// small screen size
if (screenWidth < 500 || screenHeight < 500) {
Panel_3.setVisible(false);
Panel_2.getLayout().setWidth(LayoutValue.create(98,
LayoutUnit.Percent));
Panel_2.getLayout().setBottom(LayoutValue.Auto);
Panel_2.getLayout().setHeight(LayoutValue.create(376,
LayoutUnit.Pixel));
Panel_3.getLayout().setBottom(LayoutValue.Auto);
Panel_3.getLayout().setLeft(LayoutValue.create(1,
LayoutUnit.Percent));
Panel_3.getLayout().setTop(LayoutValue.create(476,
LayoutUnit.Pixel));
if (screenWidth < 500) {
//one column
Panel_3.getLayout().setHeight(LayoutValue.create(
(baseChartHeight + padding) * 4 + padding * 3 +
Table_1.getLayout().getHeight().value, LayoutUnit.Pixel));
} else {
//two columns
Panel_3.getLayout().setHeight(LayoutValue.create(840,
LayoutUnit.Pixel));
}
Panel_3.setVisible(true);
}
With the Layout APIs, you have all the flexibility to adjust the application based on the screen size,
to create a responsive application in an analytic application.
To specify a theme, use the syntax Application.setTheme(), type CTRL+Space and the theme
selector will automatically pop up for you to choose the theme you want to apply from
the Files repository. After you choose a theme, the corresponding theme ID will be displayed in
the syntax. If you choose not to define a theme in the syntax, then the application will apply the
default light theme instead.
Note: Currently, there's a limitation that calling the setTheme() API in a popup doesn't affect the
theme settings in the popup. To solve this, you can add a panel to a popup and include all widgets
in it. Then, when you trigger the setTheme() API in a popup, all widgets added to the panel will
apply the new settings.
Here's an example that shows how to leverage the theme API to allow end users to switch
between different themes for your application:
Widget Concepts, APIs, and Usages 102
First add a dropdown widget Theme_Dropdown to the canvas. In the Builder Panel of the dropdown,
fill the value column with the theme IDs and the text column with corresponding theme names.
In addition to use the theme API, you can also enable end users to apply a specific theme when
loading an analytic application by directly adding the theme ID to the application's URL address.
For example, like this:
https://master-app-building
/sap/fpa/ui/bo/application/4FA12EC04829FDC682399273A7A3A0C?mode=embed;themeId=D991AAE
EC518947626D749EDFF57D64C
In the Styling Panel, you can enable or disable the automatic loading indicator.
Besides the configuration in the Styling Panel at design time, the automatic loading indicator can
be also turned on and off via scripting:
// Enable/disable automatic loading indicator
Application.setAutomaticBusyIndicatorEnabled(true);
The APIs are available for the following objects: Application, Popup, and container widgets, such
as TabStrip and Panel. The text shown along with the indicator can be configured via an optional
parameter.
// Show loading indicator, add text to loading indicator if text is specified
Application.showBusyIndicator("Loading the application"); // cover the whole
application page
Popup_1.showBusyIndicator("Loading the popup"); // cover the popup
TabStrip_1.showBusyIndicator("Loading the tab strip"); // cover the tab strip
Panel_1.showBusyIndicator("Loading the panel"); // cover the panel
When applying a bookmark, the operation is applied to the bookmark's Included Components
configured at design time.
// Apply the bookmark to the current analytic application. Returns false if the
bookmark is not accessible to the current user. The input is the bookmark ID or a
BookmarkInfo object.
BookmarkSet_1.apply(bookmark);
Widget Concepts, APIs, and Usages 104
Notification Panel
Email template
NotificationOptions {
title: string,
content?: string,
receivers?: string[], // default: current application user
mode?: ApplicationMode, // default: Present
parameters?: UrlParameter[], // array, no optional single URL parameter
isSendEmail?: boolean // default: false
}
Examples:
// move widget to container
Popup
There is no API to move a widget to a popup, but you can add a container (panel or tab strip) to
the popup and move the widget to this container.
You can‘t move a widget, whose parent is a popup, to other containers. For example, consider
this containment hierarchy: Popup_1 – Panel_1 – Button_1. You can‘t move Panel_1 to another
container on the canvas, but you can move Button_1.
Bookmark
You can bookmark the state after the moveWidget() API call.
Example:
Button_1 is in canvas.
Run the application. Move Button_1 to Panel_1 via the moveWidget() API. Save the bookmark.
Open the application again, move Button_1 to Panel_2 and delete Panel_1. Save the application.
In this case, it is recommended that the application developer should update the bookmark
version.
• Dropdown
• Image
• Input Field
• List Box
• Radio Button Group
• Range Slider
• Slider
• Text Area
A value that an end user selected or updated at runtime can be written back to a specific Script
Variable as well.
InputField, TextArea
• Bindable values: Text
Widget Concepts, APIs, and Usages 108
• Supported bindings: Script Variable, Tile Filter & Variable, Model Variable, Application
Property (incl. Current User/Time/Date, Last Modified Date, Last Modified Date/Time,
Last Modifier, Creator)
Slider, RangeSlider
• Bindable values: (Slider) Current value; (Range Slider) Start value, End value
• Supported Bindings: Script Variable, Tile Filter & Variable, Model Variable
Image
• Bindable values: Image URL
• Supported Bindings: Script Variable
Widget Concepts, APIs, and Usages 109
Example:
In the following example, a customer has three SAP Analytic Cloud (SAC) tenants and three 3
SAP BW landscapes (Dev, Acceptance, and Production). The customer wants the SAC analytic
applications to check from which SAC tenant an analytic application has been launched wants to
open the WebInteligence report on the corresponding SAP BW landscape with the help of the
Hyperlink functionality of the Navigation API:
// Example:
Widget Concepts, APIs, and Usages 110
You can also use the script API to suppress system messages (success, warning, info) in some
cases in order not to annoy end users. Fatal errors and reload cannot be suppressed because it
is critical to let end users know. Messages will be written to the console even if they are
suppressed by setMessageTypesToShow() for supportability reasons.
Script API
enum ApplicationMessageType {
Success,
Info,
Warning,
Error
}
New events
Application:
// triggered before Application.onResize() event
onOrientationChange(angle: DeviceOrientation)
onShake()
Button, Image, Shape:
onLongPress()
Widget Concepts, APIs, and Usages 111
For example, you can set the background color based on a value.
Before such APIs, a trick to achieve this was to create two text widgets, each with a red or green
background color. Then setVisible() was used to control which text widget should be shown.
This increased the number of widgets.
Script API
Text.setStyle({
backgroundColor: value,
color: value
}): void
InputField.setStyle({
backgroundColor: value,
borderColor: value,
color: value
}): void
TextArea.setStyle({
backgroundColor: value,
borderColor: value
}): void
Shape.setStyle({
fillColor: value,
lineColor: value
}): void
Typical Patterns and Best Practices 112
To achieve this, we will add an icon that represents a Chart and another that represents a Table.
Then, we will write scripts for each of the images/icon we added to make it so that when we click
on the Chart icon, the chart will appear, and the Table will be invisible, and vice versa.
Our default setting, shown when the application is first run, will be to make the Table visible (and
the Chart invisible).
The result will look like this when we first run the application:
And if we click on the image, we will get the Chart and the image will change its look to a
Table icon and if we select it we come back to the view of the previous screenshot:
Prerequisites for this use case is having already added a Table and a Chart to your canvas.
Please select, for example, the model BestRun_Advanced as data source.
icon to
Switch_to_Table_display and the
Chart.setVisible(true);
Table.setVisible(false);
Switch_to_Table_display.setVisible(true);
Switch_to_Chart_display.setVisible(false);
on the button.
Chart.setVisible(false);
Table.setVisible(true);
Switch_to_Table_display.setVisible(false);
Switch_to_Chart_display.setVisible(true);
Typical Patterns and Best Practices 116
In the Dropdown widget, we will load all the measures from our data set and set the default filtering
measure of the table to “Gross Margin Plan”.
When another measure is selected, the filter is applied to the Table as well as the Chart (You can
go from the Table to the Chart and vice versa using the and the icons, respectively.)
The result will look like this when we run the application:
And if we click on the Dropdown box, we will get all the measures with which we can filter the
results of the Table or the Chart:
Typical Patterns and Best Practices 117
Prerequisites for this use case is having already added a table and a chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
[Account_BestRunJ_sold].[parentId].&[Gross_MarginActual]
Typical Patterns and Best Practices 120
Table.getDataSource().setDimensionFilter("Account_BestRunJ_so
ld",selectedId);
Chart.addMeasure(selectedId, Feed.ValueAxis);
if (measures.length > 0) {
for (var i = 0; i < measures.length; i++){
// Measure
Dropdown_Measures.addItem(measures[i].id,
measures[i].description);
if (selectedKey === "" && i === 0) {
selectedKey = measures[i].id;
Dropdown_Measures.setSelectedKey(selectedKey);
console.log(["selectedKey ", selectedKey]);
}
console.log(["CurrentMeasure ", measures]);
}
}
Utils.setMeasureFilter(selectedKey);
Typical Patterns and Best Practices 123
Now let’s see how it looks like. Application when it’s first run:
Unlike a Dropdown box, the Checkbox Group allows using multiple measures as filters. In this
use case, we will add a Checkbox Group widget where we will list all the measures in our data
set. On top of that, there will be three buttons;
• “Set selected” to filter the Table and Chart using the checked measures in the Checkbox
• “Remove all” to remove all the selected filters
• “Set all” to display all the available measures in our Table/Chart
The result will look like this when we run the application:
Typical Patterns and Best Practices 124
Prerequisites for this use case is having already added a table and a chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
Chart.removeMeasure(CurrentMeasureFilterSelection[i]
, Feed.ValueAxis);
}
}
// add Measures
Table.getDataSource().setDimensionFilter("Account_Be
stRunJ_sold",selectedIds);
for (i = 0; i < selectedIds.length; i++) {
Chart.addMeasure(selectedIds[i], Feed.ValueAxis);
}
// save the current selection into global variable
CurrentMeasureFilterSelection = selectedIds;
similarly select .
Utils.setMeasureFilter(CheckboxGroup_Measures.getSel
ectedKeys());
Typical Patterns and Best Practices 131
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
Utils.setMeasureFilter(AllMeasures);
if (measures.length > 0) {
for (var i = 0; i < measures.length; i++) {
// add the Measure to checkbox group
CheckboxGroup_Measures.addItem(measures[i].id,measur
es[i].description);
//add the measure to the selecedKeys
selectedKeys.push(measures[i].id);
CheckboxGroup_Measures.setSelectedKeys(selectedKeys)
;
console.log(["CurrentMeasure ", measures]);
}
}
Now let’s see how it looks like. Application when it’s first run:
Click on Run Analytic Application in the
upper right side of the page and the result
should look something like this:
Let us only select a few measures and see Table after clicking on “Remove all”:
how the Table will change.
In the screenshot on the right, 4 measures
are chosen (Gross Margin Plan, Quantity
Sold, Original Sales Price abs Dev, and
Discount).
After selecting the measures, please click
on “set selected” to update the Table/Chart
with your chosen measures.
Instead of loading all the dimensions in our data set into a Checkbox group or a Dropdown widget,
in this use case, we will select specific dimensions to load into a Filter Line.
Typical Patterns and Best Practices 134
Unlike other data bound widgets (such as Table or Chart), R Visualization can add multiple input
data models. To support R Visualization in Filter Line, one Dropdown list is added to select the
connected input data.
After the user selects an input data model of the R Visualization widget, the Filter Line can support
R Visualization just like other widgets.
After loading the desired dimensions into our Filter Line, we will connect it to our Table/Chart/R
Visualization so that the data is filtered using the selected filter.
To use the Filter Line after running the application, simply click on the Filter Line icon and select
the dimension you want to use to filter your data.
The result will look like this when we run the application:
And this is how it will look like when we click on our Filter Line widget:
Typical Patterns and Best Practices 135
Prerequisites for this use case is having already added a Table and a Chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
the and
respectively (please refer to the
“Switching between Table and
Chart” Exercise).
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Location_4nm2e04531");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Product_3e315003an");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Sales_Manager__5w3m5d06b5");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Store_3z2g5g06m4.Store_GEOID");
Typical Patterns and Best Practices 138
We will add two Dropdown lists, one for filtering dimensions and the other for filtering hierarchies
and depending on what dimension we choose to filter on, the Dropdown List for the hierarchy
filters will change.
There is always one consistent filter for hierarchies which is Flat Presentation and according to
our chosen dimension, we might either only have that one or have more options.
For example, if we are filtering on Location, we have two choices for hierarchies: Flat Presentation
and according to States, however, if we are filtering on Product, we have Flat Presentation,
Category, or ABC (this one categorizes the dimension as “worst-selling”, “medium-selling”, or
“best-selling”), and if we are filtering on Store or Sales Manager, our only option is Flat
Presentation.
The different filters can be chosen by simply selecting them from the Dropdown lists we added.
The result will look like this when we run the application:
Prerequisites for this use case is having already added a Table and a Chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
Typical Patterns and Best Practices 140
Location_4nm2e04531 Location
Product_3e315003an Product
Store_3z2g5g06m4 Store
// Table
Table.removeDimension(CurrentDimension);
Table.addDimensionToRows(sel);
//Chart
Chart.removeDimension(CurrentDimension, Feed.CategoryAxis);
Chart.addDimension(sel, Feed.CategoryAxis);
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id, 'Flat
Presentation');
}
else {
Typical Patterns and Best Practices 144
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ', CurrentDimension]);
// Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
// Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id, 'Flat
Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ', CurrentDimension]);
//Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 146
The user can select which measures they would like displayed in the Table through the Measures
Checkbox and then through another Checkbox, they could decide which dimensions they want
displayed on the columns or the rows of the Table.
The application also makes it easier for the user to select all or remove all measures by adding
buttons specifically for that purpose.
They can also remove the dimensions that they added to the columns and rows and are able to
choose to add them again afterwards.
The result will look like this when we run the application:
Typical Patterns and Best Practices 147
This application assumes that there already is a Table in your canvas. To match the scripts in the
application it is recommended to rename the widget to Table.
Typical Patterns and Best Practices 148
CheckboxGroup_Columns.removeAllItems();
CheckboxGroup_Rows.removeAllItems();
CheckboxGroup_Free.removeAllItems();
CurrentDimensionColumn = ArrayUtils.create(Type.string);
CurrentDimensionRows = ArrayUtils.create(Type.string);
console.log(["CurrentDimensionColumn should empty",
CurrentDimensionColumn.slice()]);
console.log(["CurrentDimensionRows should empty",
CurrentDimensionRows.slice()]);
// Dimension in Columns
var dimCol = Table.getDimensionsOnColumns();
if (dimCol.length > 0) {
for (var i = 0; i < dimCol.length; i++) {
CurrentDimensionColumn.push(dimCol[i]);
console.log(["CurrentDimensionColumn ", dimCol[i]]);
}
}
Typical Patterns and Best Practices 161
// Dimension in Rows
var dimRows = Table.getDimensionsOnRows();
if (dimRows.length > 0) {
for (i = 0; i < dimRows.length; i++) {
CurrentDimensionRows.push(dimRows[i]);
console.log(["CurrentDimensionRows ", dimRows[i]]);
}
}
CheckboxGroup_AllDimensions.setSelectedKeys([AllDimension
s[i]]);
var dimdesc =
CheckboxGroup_AllDimensions.getSelectedTexts();
CheckboxGroup_Free.addItem(AllDimensions[i],
dimdesc[0]);
console.log(["AllDimensions",AllDimensions[i],
dimdesc[0]]);
}
}
}
console.log(["CurrentDimensionColumn",
CurrentDimensionColumn]);
console.log(["CurrentDimensionRows",
CurrentDimensionRows]);
CheckboxGroup_Free.setSelectedKeys([CurrentDimensionRows[
i]]);
dimdesc = CheckboxGroup_Free.getSelectedTexts();
CheckboxGroup_Rows.addItem(CurrentDimensionRows[i],
dimdesc[0]);
CheckboxGroup_Free.removeItem(CurrentDimensionRows[i]);
}
}
}
if (CurrentDimensionColumn.length > 0) {
for (i = 0; i < CurrentDimensionColumn.length; i++) {
if (CurrentDimensionColumn[i] !== "") {
CheckboxGroup_Free.setSelectedKeys([CurrentDimensionColum
n[i]]);
dimdesc = CheckboxGroup_Free.getSelectedTexts();
CheckboxGroup_Columns.addItem(CurrentDimensionColumn[i],
dimdesc[0]);
CheckboxGroup_Free.removeItem(CurrentDimensionColumn[i]);
}
}
}
Typical Patterns and Best Practices 162
Utils.setMeasureFilter(CheckboxGroup_Measures.getSelected
Keys());
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
Utils.setMeasureFilter(AllMeasures);
Utils.setDimensionCheckboxes();
Utils.setDimensionCheckboxes();
Typical Patterns and Best Practices 164
Utils.setDimensionCheckboxes();
Utils.setMeasureFilter(selectedKeys);
Utils.setDimensionCheckboxes();
Typical Patterns and Best Practices 166
In this use case, we want to be able to filter our table and chart according to certain measure
groups of our data set. Here, Gross Margin, Discount, Quantity Sold, and Original Sales Price are
the options.
These measure groups are going to be selected from a Dropdown list in our canvas.
Afterwards, we will use the popup widget to switch between Table and Chart using a Radio Button
Group and give the user the ability to control the measures (Actual, Plan, Absolute, and % of
Deviation) of the measure groups using a Checkbox Group widget.
The result will look like this when we run the application:
Typical Patterns and Best Practices 168
And when the Settings button is clicked, the application will display the popup with the
settings that the user can change:
Prerequisites for this use case is having already added a table and a chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
Typical Patterns and Best Practices 169
There, enter
“Dropdown_MeasureGroup” as the
Name.
Typical Patterns and Best Practices 170
Actual Actual
Plan Plan
_Abs Absolute
_Percent % Deviation
Popup_Settings.open();
Table.getDataSource().setDimensionFilter("Account_Bes
tRunJ_sold", selectedId);
Chart.addMeasure(selectedId, Feed.ValueAxis);
Typical Patterns and Best Practices 180
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup === 'Discount') {
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[DiscountActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[DiscountPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Discount_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Discount_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup === 'Quantity_Sold') {
Typical Patterns and Best Practices 181
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup ===
'Original_Sales_Price') {
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PriceActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PricePlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Percent]", Feed.ValueAxis);
}
Chart.removeMeasure(CurrentMeasureFilterSelectionPopu
p[i], Feed.ValueAxis);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = ArrayUtils.create(Type.string);
CurrentMeasureSelection = Selected_Measures;
Chart.removeMeasure(CurrentMeasureFilterSelectionPopu
p[i], Feed.ValueAxis);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = ArrayUtils.create(Type.string);
Table.getDataSource().removeDimensionFilter("Account_
BestRunJ_sold");
Table.getDataSource().setDimensionFilter("Account_Bes
tRunJ_sold", Filter_Area);
In a Table, a user will be able to select a measure cell, a dimension cell, or a data cell. Each will
open a popup window that displays information about the selected element in a trend chart.
In the Chart, a user will be able to select a dimension cell and a measure/dimension chart bar (for
example, Gross Margin Plan for Lemonade).
There are also two Dropdown lists, one for dimensions and the other for hierarchies. The list of
dimensions let the user choose which dimension filter they want to use on the Table/Chart. In this
use case, we have chosen 4 dimensions; Location, Product, Store, and Sales Manager.
The second Dropdown list displays the available hierarchies that can be used to change how the
data is displayed.
Note: In this example, only single selection is supported for the Table and Chart.
The result will look like this when we run the application:
And when a cell is chosen, a popup window like the one in the screenshot will appear (In this
screenshot, the dimension cell of Los Angeles was clicked on in the Table):
Typical Patterns and Best Practices 187
Prerequisites for this use case is having already added a functioning Table and a Chart to your
canvas. To have all the functionalities in this use case, please first go through the Switching
between Table and Chart exercise.
It is recommended to use the same names as that exercise for the Table and Chart so that the
scripts in this use case don’t have to be altered.
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
'Flat Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ',
CurrentDimension]);
Details_Chart.removeMeasure(CurrentMeasures[i],
Feed.ValueAxis);
Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
}
//Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
CurrentDetailsMeasures.push(memberId);
Typical Patterns and Best Practices 199
Popup_show = true;
}
// Dimension
else {
console.log(['Selection Dimension: ',
dimensionId]);
console.log(['Selection Member: ', memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
if (Popup_show === true) {
Popup_Details.open();
}
if (sel.length > 0) {
Details_Chart.getDataSource().removeDimensionFilter(C
urrentDimension);
Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
CurrentDetailsMeasures.push(memberId);
Popup_show = true;
}
Typical Patterns and Best Practices 201
// Dimension
else {
console.log(['Selection Dimension: ',
dimensionId]);
console.log(['Selection Member: ',
memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
}
Details_Chart.removeMeasure(CurrentDetailsMeasures[i]
, Feed.ValueAxis);
}
CurrentDetailsMeasures =
ArrayUtils.create(Type.string);
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
'Flat Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ',
CurrentDimension]);
//Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 204
//Details_Chart
Details_Chart.getDataSource().setHierarchy(CurrentDim
ension, '__FLAT__');
In the canvas, we will add a Table with our top 10 customers as well as a Chart with the complaints
of the customers. Other than that, we will have two R Visualization widgets through which we will
create word clouds that change the size of the words displayed according to the frequency with
which they appear in the data set.
Further functionalities in this application include how to filter widgets according to a selected
element of a Table and how we can change the color of the word clouds through external input
(in this use case, it is achieved through a Radio Button Group that has a script that passes the
value to the R widgets.)
And lastly, the filtering of all the widgets in the canvas using Radio Button Groups will be explored
(here, we will filter according to Regions and according to the selected Region, several countries
from that Region will be displayed in another Radio Button Group (Country) for further filtering of
the widgets).
The result will look like this when we run the application:
There are no prerequisites for this use case. You can start with a new application.
It is recommended to use the same names as that exercise for the used widgets so that the scripts
in this use case don’t have to be altered.
There, enter
“RadioButtonGroup_Region” as the
Name, choose Vertical Layout as the
Display Option, and toggle the Label
Text button to enable it and write
“Region” as the Label Text.
Typical Patterns and Best Practices 210
REGION01 LATAM
REGION02 EMEA
REGION03 NA
REGION04 APJ
There, enter
“RadioButtonGroup_Country” as the
Name, choose Vertical Layout as the
Display Option, and toggle the Label
Text button to enable it and write
“Country” as the Label Text.
ALL All
# load package
library(wordcloud)
# get words
words <- BestRunBike_Customer_Complaint$`Complaint
Category`
# get frequency
frequency <- BestRunBike_Customer_Complaint$Count
if (exists("colorValue")) {
myColor <- colorValue
} else {
myColor <- "Oranges"
}
# generate word cloud
wordcloud(words, frequency, scale = c(4, 1),
rot.per=0.2, colors=brewer.pal(8, myColor))
# get words
words <- BestRunBike_Customer_Complaint$`Complaint
Category`
# get frequency
frequency <- BestRunBike_Customer_Complaint$Count
if (exists("colValue")) {
myColor <- colValue
} else {
myColor <- "Oranges"
}
# generate word cloud
wordcloud(words, frequency, scale = c(4, 1),
rot.per=0.2, colors=brewer.pal(8, myColor))
if (sel.length > 0) {
var selection = sel[0];
console.log(['Selection [0] : ', selection]);
Chart_Complaints.getDataSource().setDimensionFilter(dim
ensionId, memberId);
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r(dimensionId, memberId);
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r(dimensionId, memberId);
Hidden_DropDown_Customer.setSelectedKey(memberId);
var text =
Hidden_DropDown_Customer.getSelectedText();
Title_Complaints.applyText("Complaints for Customer
" + text);
}
}
RadioButtonGroup_Country.removeAllItems();
RadioButtonGroup_Country.addItem("ALL", "All");
RadioButtonGroup_Country.setSelectedKey("ALL");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY011]", "Mexico");
} else if (sel === "REGION02") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY021]", "Dubai");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY022]", "Germany");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY023]", "Great Britian");
} else if (sel === "REGION03") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY031]", "USA East");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY032]", "USA West");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY033]", "Canada");
} else if (sel === "REGION04") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY041]", "India");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY042]", "China");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY043]", "Australia");
}
Table_Customer.getDataSource().setDimensionFilter("Regi
on",sel);
Chart_Complaints.getDataSource().setDimensionFilter("Re
gion",sel);
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Region",sel);
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Region",sel);
Table_Customer.getDataSource().removeDimensionFilter("C
ountry");
Typical Patterns and Best Practices 226
Chart_Complaints.getDataSource().removeDimensionFilter(
"Country");
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().removeDimensionFi
lter("Country");
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().removeDimensionFi
lter("Country");
Table_Customer.getDataSource().removeDimensionFilter("C
ountry");
Chart_Complaints.getDataSource().removeDimensionFilter(
"Country");
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().removeDimensionFi
lter("Country");
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().removeDimensionFi
lter("Country");
} else {
Table_Customer.getDataSource().setDimensionFilter("Coun
try", sel);
Chart_Complaints.getDataSource().setDimensionFilter("Co
untry", sel);
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Country", cloud_sel);
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Country", cloud_sel);
}
Typical Patterns and Best Practices 227
RVisualization_WordCloud_2018.getInputParameters().setS
tring("colorValue", sel);
RVisualization_WordCloud_2019.getInputParameters().setS
tring("colValue", sel);
var list =
Table_Customer.getDataSource().getMembers("Customer_",
1000);
if (list.length !== 0) {
for (var i = 0; i < list.length; i++) {
console.log(['List Dimension: ', i ,
list[i].displayId]);
console.log(['List Description: ', i ,
list[i].description]);
console.log(['List Member: ', i , list[i].id]);
Hidden_DropDown_Customer.addItem(list[i].id,
list[i].description);
}
}
Typical Patterns and Best Practices 228
If the passed value is prefixed with an asterisk ( *), then the value is applied as a factor to the
present cell value. For example, applying the following script after the script above
Table_1.getPlanning().setUserInput({"sap.epm:Account":
"[sap.epm:Account].[parentId].&[TAXES]", "sap.epm:ProfitAndLoss_Version02":
"public.Actual"}, "*0.5");
Table_1.getPlanning().submitData();
results in a cell value (raw value) of 61728394.5, which is displayed as 61.73 (formatted value).
Another example shows a combination of a table with an input field. The value of the input field is
applied as the new cell value to the first selected cell of the table:
var selectedCell = Table_1.getSelections()[0];
Typical Patterns and Best Practices 229
7 Planning
And what can you not expect? In analytics designer you cannot use Input Tasks and Planning
scripting is not possible for models based on BPC Write-Back.
These icons are greyed out if no table cell with a planning model is selected.
To get the Planning Table object, use the script below. If the table has no planning model
assigned, it will return undefined.
Table.getPlanning(): Planning | undefined
Scripting will perform the same planning actions that could be done via UI. The benefits of
scripting are augmented in cases which you want to minimize the number of clicks from your user,
personalize your UI or when a special customer requirement can’t be fulfilled with standard
planning behavior.
Data can’t be changed during design time, and you can enable the usage of planning features
during runtime in two different ways:
• In the table designer UI: You can find in the Builder panel, section Properties, a box
called Planning enabled.
Planning 231
One other valuable script allows checking whether the data model is planning enabled:
isEnabled(): boolean
In the Table Builder panel, there are some configurations that you can do in each dimension, and
Unbooked Data might be a good choice when, for example, your Planning Data Model has no
booked data and your end users need to see which dimension members are available for
planning.
The picture below represents the scenario mentioned above to explain this feature:
In this example, the following scripting would be included on the Save Data button.
Regarding data formatting – it takes as parameter either a raw value in the user formatting setting
(“1234.567” with “.” grouping separator) or a scale in the user formatting setting (for example,
“*0.5” to divide the value by half or “*2” to double the value) – both of type string.
To submit the updated cell data with all the beforehand modified data and to trigger refresh of
data:
submitData(): boolean
But to make this data visible to other users, you can publish the public versions through the
following toolbar icon:
After clicking this icon, the dialog below is opened and an action can be taken per model. You
can also revert, and all data changes will be discarded.
The actions performed within this dialog can also be done via the below scripting on public
versions:
revert(): boolean
publish(): boolean
After the execution of these scripts, a message informs whether the script ended successfully or
not. These are the expected messages:
If the version was not modified before these actions are triggered, the message below should be
expected:
It is also possible to publish private versions via the two scripting options below:
publish(): boolean
publishAs(newVersionName: String, versionCategory: PlanningCategory): boolean
In the second option, a version name is given, and a new public version is created under the
informed version category.
These scripts can be very useful if your planning model is placed in a popup, for example. As the
toolbar is kept in the background canvas, users don’t need to close the popup to then publish the
data. With scripting, you can do it directly in the popup!
Planning 236
Find in the next section more information about version category and how to create private
versions.
7.6.2 Copy
Data models with planning enabled capability have one dimension in common, the version. And
each version is classified in one of the following planning categories:
• Actual
• Planning
• Budget
• Forecast
• Rolling Forecast
PlanningCopyOptions offers you the possibility to either create a new empty version or to copy all
data from the source version. In case you want to create a private copy of any version, use the
script below:
copy(newVersionName: string, planningCopyOption: PlanningCopyOption,
versionCategory?: PlanningCategory): boolean
• Table.getPlanning().getDataLocking()
• Table.getPlanning().getDataLocking.getState()
• Table.getPlanning().getDataLocking.setState()
This check is necessary because a user can’t perform certain operations on a table, like
setState() and getState(), if the model is not data locking enabled.
In the following example, the data locking object is retrieved and printed to the console. A data
locking object is returned if data locking is enabled on the model.
var planning = Table_1.getPlanning();
console.log(planning.getDataLocking());
Note that you can also check if a model is data locking enabled in SAP Analytic Cloud by checking
the model preferences (see Figure 84).
In following example, the data locking state for a selected cell of a table is retrieved:
var selection = Table_1.getSelections()[0];
var selectionLockState =
Table_1.getPlanning().getDataLocking().getState(selection);
Planning 238
In order to create a selection on the table, you can either select the cell in the table manually or
you can create the selection string yourself in the script editor.
If the state of the selection can't be determined, then the method returns undefined. This occurs
if one of the following situations applies:
• The selection is invalid.
• The cell referenced by the selection is not found.
• The cell is in an unknown state.
• The cell has been created using "Add Calculation" at runtime.
If you have activated the Show Locks option for the table, then the “lock” icons will be updated
after the method has finished running.
The method returns true if the set operation was successful and false otherwise.
You can't set the data locking state on a private version. In this case, the following message is
displayed:
“You can only set data locks on public versions. Please use a public version and try again.”
If you attempt to set the data locking state DataLockingState.Mixed, then the following message
is displayed:
“You can't set the state with the value 'mixed'. Please specify either 'open', 'restricted' or 'locked'
as value.”
The same message is displayed at runtime if you attempt to execute the script and the script fails.
If you select multiple cells and attempt to set the data locking state, the data locking state will be
applied to the first selection only.
In the following example, the data locking state is set for a selected table cell:
var selection = Table_1.getSelections()[0];
var isSetStateSuccessful =
Table_1.getPlanning().getDataLocking().setState(selection,
DataLockingState.Locked);
Planning 239
Note that if data locking is disabled for a model, all locks will be deleted. If it is turned on again
later, all members are reset to their default locking state. The same happens if the default locking
state or driving dimensions are changed.
7.8.1 BpcPlanningSequence
onBeforeExecute
onBeforeExecute(): boolean
Called when the user clicks the BPC planning sequence trigger. If the method returns true or
returns no value, then the BPC planning sequence is executed. If the method returns false, then
the BPC planning sequence is ignored.
7.8.2 DataActionTrigger
onBeforeExecute
onBeforeExecute(): boolean
Called when the user clicks the data action trigger. If the method returns true or returns no value,
then the data action is executed. If the method returns false, then the data action is ignored.
Examples:
In the following example, a new planning member is added to the dimension “LOCATION” of a
planning model:
PlanningModel_1.createMembers("LOCATION", {
id: "BERLIN",
description: "Berlin"
});
In the following example, the new planning member is updated by adding a data locking owner:
PlanningModel_1.updateMembers("LOCATION", {
id: "BERLIN",
dataLockingOwners: [{
id: "ADMIN",
type: UserType.User
}]
});
Planning 240
In the following example, the description of the new planning member is printed to the browser
console:
var member = PlanningModel_1.getMember("LOCATION", "BERLIN");
console.log(member.description);
In the following example, the fifth up to the twelfth member of dimension “LOCATION” is returned:
var members = PlanningModel_1.getMembers("LOCATION", {
offset: "4",
limit: "8"
});
The first member has an offset of 0, so the fifth member has an offset of 4. Starting at this offset,
we return the next 8 members.
The PlanningModel API provides many more features. See the online API reference for more
information.
Note: You can add members to dimensions of type “Generic” only (see the SAP Analytics Cloud
modeler). Adding members to dimension of other types, such as, for example, “Account”,
“Version”, “Time”, or “Organization” isn’t supported.
Note: After you have added members to a very large model (with millions of members) and have
refreshed the model with Application.refreshData() or DataSource.refreshData(), it may happen
that not all added members are immediately displayed, for example, in a table associated with
the planning model. The same applies to updating members. This is because these operations
work asynchronously in the background. Repeat your refresh operation after a short while.
responsible Responsible
Note: When you add your own properties to planning members, use a prefix to avoid name
conflicts with existing properties of planning members.
Predictive 241
8 Predictive
In analytics designer, there are several predictive features that can help you to explore the data
and gain more insights.
Basically, Time Series Forecast can be switched on and off via two ways: the entry in context
menu at both design time and runtime,
The number of periods to predict can be configured via two ways: the entry in Chart Details at
both design time and runtime,
Predictive 242
Figure 87: Time Series Chart: Select the Interested Data Point
Predictive 243
Basically, Smart Grouping can be switched on and off via two ways: the setting in Builder Panel
at design time,
Sample Gain insights into the data demonstrates how to trigger Smart Discovery via APIs.
var ds = Chart_Forecast.getDataSource();
var members = ds.getMembers("Product_3e315003an");
var SDsetting = SmartDiscoveryDimensionSettings.create(ds, "Product_3e315003an",
[members[1]]);
SDsetting.setIncludedDimensions(["Location_4nm2e04531", "Store_3z2g5g06m4"]);
Predictive 245
SDsetting.setIncludedMeasures(["[Account_BestRunJ_sold].[parentId].&[Gross_Margin]"
, "[Account_BestRunJ_sold].[parentId].&[Discount]"]);
SmartDiscovery.buildStory(SDsetting);
In this example, Smart Discovery is invoked via clicking “More Insights…” to discover Product
with Dark Beer as the target group. In addition, two more measures (Gross Margin and Discount)
and two more dimensions (Location and Store) are included in the analysis.
Write Analytic Design scripts to launch Search To Insight. At runtime, the analytic application user
can open the Search To Insight dialog to get deep and flexible insights of their data.
var mode = SearchToInsightDialogMode.Simple;
SearchToInsight_1.openDialog("Gross Margin by Location", mode, true, true);
You can also apply Search To Insight results to a chart using the applySearchToChart() API and
leverage the following variable related APIs to save variable value in a Search To Insight
component and apply to chart when calling applySearchToChart():
// get model variable
SearchToInsight_1.getVariables(modelId: string): VariableInfo[]
In this example, you can design a simple application to let application users trigger different
modes of Search To Insight for the questions they enter.
First, in addition to the scripting object SearchToInsight_1, add an input field InputField_1, a
button Button_1 and a checkbox group CheckboxGroup_1 to the canvas as below:
Then write the following script for the button widget Button_1:
var mode = SearchToInsightDialogMode.Simple;
if (CheckboxGroup_1.getSelectedKeys().length !== 0) {
mode = SearchToInsightDialogMode.Advanced;
}
var inputText = InputField_1.getValue();
SearchToInsight_1.openDialog(inputText, mode, false, true);
Result: After you save the application and choose Run Analytic Application, application users can
either trigger simple mode by entering a question and clicking the Search To Insight button, or
trigger advanced mode by entering a question, selecting Advanced mode, then clicking the
Search To Insight button.
Example 2: Receive Question from Host HTML Page and Apply Search To Insight Results
to a Chart
In this example, you can build your own Search To Insight user interface and integrate Search To
Insight results to your own portal.
Predictive 248
First, embed your analytic application in your own portal via iFrame and maintain the
corresponding code to get the message users input in the portal and post it to the embedded
analytic application.
Then go back to the analytic application. Besides adding the scripting object SearchToInsight_1,
write the following script for the onPostMessageReceived event of the application:
SearchToInsight_1.applySearchToChart(message, Chart_1);
Chart_1.setVisible(true);
Result: After that in your own portal, users can ask a question and see the chart of the embedded
analytic application appear and display corresponding Search To Insight results.
OData 249
9 OData
Versions 1.0, 2.0, and 3.0 are released under the Microsoft Open Specification Promise.
Version 4.0 was standardized at OASIS, with a release in March 2014. In April 2015 OASIS
submitted OData v4 and OData JSON Format v4 to ISO/IEC JTC 1 for approval as an
international standard.
“The protocol enables the creation and consumption of REST APIs, which allow Web clients to
publish and edit resources, identified using URLs and defined in a data model, using simple HTTP
messages. OData shares some similarities with JDBC and with ODBC; like ODBC, OData is not
limited to relational databases.”
Source: https://en.wikipedia.org/wiki/Open_Data_Protocol
For OData, CORS should be configured on the backend analogous to an InA connection plus
support for “if-match” as allowed header.
• For actions with optional parameters of unsupported types, the parameters will not be
available but the action itself will.
• In case of bound actions, only binding on entity types (passable by key) will be supported.
• Only the JSON format will be supported.
• Only the following system types are supported:
o SAP S/4HANA On-Premise
o SAP BW
o SAP HANA
o SAP Business and Consolidation (BPC)
• Only Direct (CORS) connections will be supported. No Path (Proxy), as this feature is
being deprecated.
Script execution will block waiting on the response of a triggered action. For now, the assumption
is that actions triggering long-running processes return quickly (although the process may not yet
be complete). So, while of course the XHR invoking the action is asynchronous, script execution
will block waiting for the response, to allow the script writer to react to the return value of the
action.
In general, actions can be bound on every type, but we support only binding on single entities.
In Analytics Designer OData actions can be called from and executed in the backend system via
scripting inside an analytic application. Also, programmatic read access to OData services is
provided.
OData 251
In your analytic application in the Layout Outline in the Scripting Section you can create a new
OData Service by clicking on plus.
Once you have clicked a new entry with the default name ODataService_1 will appear below the
node. You will see a context menu indicated with three points when hovering over the name,
where you do the following actions: Rename, Find References, or Delete.
At the same time the side panel opens on the right side. It opens every time you click on the
OData Service in the Outline. In the side panel you can change the name, select the System from
the list of available systems whose connections are already created in SAC under Connections,
and specify the End-Point URL of the OData Service manually.
OData 252
Note: You need to know the URL. So far there is no browse catalog implemented.
To see the metadata of the OData Service you must click the refresh button next to Metadata.
Click on Done to close the panel.
In the example you see System FUB, the End-Point URL for this OData Service and as Metadata
you got the information that this Service is based on OData Version V.4 and it has 2 Actions called
Flight/Book and CancelMyFlights.
OData 253
Now you can insert a Button Widget and change the text of the Button in the Analytics Designer
Properties of Styling Panel to Cancel Flight.
Start the script editor by clicking the icon in the quick action menu of the widget to create a
script which triggers the execution of the action in the source system.
The script editor opens. You can open it as well by hovering over the widget in the outline and
clicking the icon.
Type in the name of the OData Service you have specified. The script editor assists you with code
completion and value help wherever possible when you click CTRL+Space.
Now you can insert another button, rename the text to Book Flight in the Styling Panel and open
the script editor. The BookFlight Action is a bound action which is much more complex than the
first one.
Congratulations. You finished the second more complex OData action and now you can run your
application and book and cancel a flight for the selected values.
You can enhance your application and start using other script methods to fill the parameter values
dynamically with local or global variables.
Also, you can make the response from the backend system visible in the app by writing the
response as message in a text field.
Insert six Text widgets on the canvas and rename the last one to MessageBox.
OData 256
var totalnumberofseats =
ConvertUtils.integerToString(ret.value[0].Totalnumberofseats);
var currency = ret.value[0].Currency;
info = "Your flight price was " + flightprice + " " + currency +
". " + "There are " + numberofoccupiedseats +
" occupied from " + totalnumberofseats + " seats in total.";
}
Text_5.applyText("" + info);
Run the application and book a flight and cancel a flight to see the error messages.
To create a meaningful application in the sense of an intelligent application, the best would be to
display the backend data via a live connection to a BEx Query. Like this you would be able to see
the changes (the booked and canceled seats) in the data directly after clicking the buttons and
executing the actions.
Therefore, in Analytics Designer you have programmatic access to these data, which can be used
for any purpose beyond the visualization in a table or a chart. For example, you can read and
display one member in a text widget.
You can focus on the following capabilities regarding access to OData entity sets:
ODataError: {
code: string;
message: string;
target: string;
details: ODataError[];
}
OData 258
Example
ODataService_1.getEntitiesFromEntitySet("Equipments");
Example
In the following example a list of Entities is returned, filtered by the specified query options:
ODataService_1.getEntitiesFromEntitySet("Departments", {filter: "contains(Sector,
'Consulting')", orderby: "Sector asc"});
Example
In the following example, the number of entities in the entity set "TEAMS" is returned:
ODataService_2.getEntitiesCountFromEntitySet("TEAMS");
In the following example, the number of entities in the entity set "TEAMS" is returned, where the
first five entities are skipped and the next ten entries are returned:
ODataService_2.getEntitiesCountFromEntitySet("EMPLOYEES", {skip: 5, top: 10});
OData 259
Using the posting message API, you as the application developer can realize either of the
following scenarios:
Then you can trigger bi-directional communication between the host HTML page and analytic
application using the provided functions.
10.1.1 postMessage
This is to post messages from the analytic application to the host HTML page.
When an end user triggers a callback function on the side of the analytic application, the callback
function sends out data to notify the parent receiver page which hosts the iFrame, or, when there
are multiple levels of web pages embedded in one another, to the top-level HTML page of a
specific target origin.
You define whether to send data to a parent or the top HTML page by means of the parameter of
the PostMessageReceiver.
Post Message API 261
10.1.2 onPostMessageReceived
This is to handle messages sent from the host parent or top HTML page in the analytic application.
In scenario 2 depicted below, the event can also handle messages sent from an HTML page
embedded via the web page widget in an analytic application.
Note: We advise you always to check the origin when receiving an event-triggered message,
because a malicious site can change the location of the window and therefore intercept the data
you sent using the postMessage event without your knowledge.
In the current scenario, the parent window which hosts the iFrame can post messages to the
analytic application's iFrame window of specific target origin. The messages posted are then
retrieved by the analytic application and trigger changes accordingly, such as updating some input
data.
10.1.3 Example
You can embed an analytic application in a host HTML page. The URL of the host HTML page is
http://localhost:8080.
First, you want to allow end users to post the company selection in the analytic application to the
host HTML page. Write the script below for the sending button:
var message = RadioButtonGroup_Company.getSelectedText();
Application.postMessage(PostMessageReceiver.Parent, message,
"http://localhost:8080");
Then you want to allow end users to display the message received from the Host HTML page in
a text box of the embedded analytic application.
if (origin == "http://localhost:8080") {
Text_ReceivedMessage.applyText(message);
}
The event for handling messages sent from embedded application is: Once the messages is
received, the host application can use the event onPostMessageReceived() to handle the
messages.
Scheduling a Publication 264
11 Scheduling a Publication
To share an analytic application with other users as well as external users via e-mails at a specific
start time and with a specific recurrence, you can schedule an analytic application for publication.
Recipients will receive an e-mail with a link to the analytic application (if so configured) and an
exported PDF file as an attachment.
Once a publication is scheduled, the related task will be available in Calendar. The Design Panel
of this task will have the same configurations as those in Schedule Publication dialog. The
configurations are editable if the task isn't complete, and read-only if it's done.
12.1.2 Browser
• Use a Google Chrome (or a Chromium-based) browser.
12.2.2 Charts
• Reduce the number of charts. This reduces the amount of transferred data.
• Reduce the number of visible data points.
12.2.3 Tables
• Reduce the number of tables. This reduces the amount of transferred data.
• Limit tables to 500 rows and 60 columns.
12.2.4 Images
• Consider limiting the size of images to less than 1MB.
• Prefer image file formats in the order: SVG, PNG, JPG.
12.2.5 GeoMaps
• When using a Bubble Layer, turn on Location Clustering. Enter 1000 for Maximum
Display Points. Both reduces the amount of transferred data.
• When working with thousands of locations consider using the Choropleth Layer.
In former releases, all widgets (visible or invisible) had to be initialized before the analytic
application started, that is, before the end user saw the startup screen.
Performance Best Practices 270
Now, you as the application designer can change this default behavior by activating loading
invisible widgets in the background. All widgets that are initially visible are initialized and displayed
to the end user. After that, the invisible widgets are initialized in the background to be available
when the end user changes their visibility. Invisible widgets are not only widgets with the flag
Show this item at view time turned off but also widgets inside invisible panels or on tabs in tab
strips that are inactive at startup. This new loading behavior increases the perceived startup
performance of the analytic application because the startup screen appears faster.
You can change to the new behavior using the Analytic Application Settings dialog:
You can overwrite this setting with the URL parameter loadInvisibleWidgets, This is useful, for
example, if you as an application designer want to decide which mode is better working with your
analytic application or if you as an end user aren’t satisfied with the choice of the application
designer. There are two possible values:
The following value forces the “classic” default behavior and loads all widgets before any of the
widgets are displayed to the end user:
loadInvisibleWidgets=onInitialization
The following value forces the background loading of invisible widgets after initially the visible
widgets are displayed to the end user:
loadInvisibleWidgets=inBackground
Performance Best Practices 271
If the mode Load invisible widgets in background is used, it is possible that a script tries to access
a widget which doesn’t exist at this point in time. This applies especially to the onInitialization
event script. Here are some best practices to reveal the full potential of this optimization:
• Leave the onInitialization event script empty.
• If this isn’t possible, try to avoid accessing initially invisible widgets. Especially avoid
using the setVariableValue() method if not needed. If you need to set a variable initially
to a static value, set the variable value state at design time in the analytic application or
via a URL parameter instead.
• If you need to configure invisible widgets via scripting (that includes setting filters or
variables), then do this directly before the widget becomes visible (for example, before
calling setVisible(true) or before changing the tab in a tab strip).
• If you must access an invisible widget in the onInitialization event script, avoid nesting
this widget too deep into a container structure, like, for example, in panels or tab strips.
Ideally, the widget should be a direct child of the canvas. You can make these widgets
visible and place them behind other widgets to make them invisible to the end user but
technically visible at startup.
12.3 Scripting
The following best practices apply to scripting in analytic applications.
If you use many widgets based on one model and they aren’t visible at the same time, it can be
better to use widget level variables to avoid implicit setting of variables on invisible widgets.
https://help.sap.com/viewer/a4406994704e4af5a8559a640b496468/release/en-
US/3fa25603111049fba11eb898ccfabbb3.html.
Note: In the example URLs of this help page replace the fragment story with application.
Example:
In the following example, the variable Manager with value ["SM1","SM2"] of model
view:[_SYS_BIC][t.TEST][remotejuice] is passed via URL (the URL isn’t functional out of the
box as there are placeholders present for the tenant’s SAP Analytics Cloud URL, the tenant ID,
and the application ID):
https://<TENANT>/sap/fpa/ui/tenants/<TENANT_ID>/bo/application/<APPLICATION_ID>?v01
Model=view:[_SYS_BIC][t.TEST][remotejuice]&v01Par=Manager&v01Val=["SM1","SM2"]
Example:
// BAD
for (var i = 0; i < dimensions.length; i++) {
Table_1.getDataSource().setDimensionFilter(dimensions[i], value);
}
// GOOD
var ds = Table_1.getDataSource();
for (var i = 0; i < dimensions.lenght; i++) {
Performance Best Practices 273
ds.setDimensionFilter(dimensions[i], value);
}
The End and the Future 274
14 Important Links
Please open the SAP Help page to find many more information about SAP Analytics Cloud,
analytics designer:
https://help.sap.com/viewer/product/SAP_ANALYTICS_CLOUD/release/en-US
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company.
The information contained herein may be changed without prior notice. Some software products marketed by SAP SE and its distributors contain proprietary
software components of other software vendors. National product specifications may vary.
These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP or
its affiliated companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP or SAP affiliate company products and
services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as
constituting an additional warranty.
In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to
develop or release any functionality mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible
future developments, products, and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies
at any time for any reason without notice. The information in this document is not a commitment, promise, or legal obligation to deliver any material, code, or
functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectations.
Readers are cautioned not to place undue reliance on these forward-looking statements, and they should not be relied upon in making purchasing decisions.
SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP
affiliate company) in Germany and other countries. All other product and service names mentioned are the trademarks of their respective companies. See
www.sap.com/copyright for additional trademark information and notices.