SAP Analytics Cloud Developer Guide
SAP Analytics Cloud Developer Guide
Developer Handbook
Table of Contents
Table of Contents .........................................................................................................................1
Figures ..........................................................................................................................................7
7 Planning ........................................................................................................................215
7.1 What to Expect from Analytics Designer Regarding Planning? .....................................215
7.2 Basic Planning Concepts in Analytics Designer ............................................................215
7.3 Refreshing Your Data ....................................................................................................217
7.4 Set User Input ................................................................................................................217
7.5 Planning Versions ..........................................................................................................218
7.5.1 Private Versions .............................................................................................................218
7.5.2 Public Versions ..............................................................................................................218
7.6 How to Manage Versions ...............................................................................................219
7.6.1 Publishing and Reverting Data Changes .......................................................................219
7.6.2 Copy ...............................................................................................................................221
Table of Contents 5
8 Predictive ......................................................................................................................225
8.1 Time Series Forecast .....................................................................................................225
8.1.1 Switch On and Off Forecast ...........................................................................................225
8.1.2 Configure Forecast ........................................................................................................225
8.2 Smart Insights ................................................................................................................226
8.2.1 Discover per Selected Data Point ..................................................................................226
8.3 Smart Grouping ..............................................................................................................227
8.3.1 Switch On and Off Smart Grouping ...............................................................................227
8.3.2 Configure Smart Grouping .............................................................................................228
8.4 Smart Discovery .............................................................................................................228
8.5 Search To Insight ...........................................................................................................229
9 OData.............................................................................................................................233
9.1 What You Should Know About OData ...........................................................................233
9.2 How You Can Connect to OData ...................................................................................233
9.2.1 What You Need to Do ....................................................................................................233
9.2.2 Known Restrictions ........................................................................................................233
9.2.3 What Is an Action? .........................................................................................................234
9.2.4 What Are Action Imports? ..............................................................................................234
9.2.5 What Is a Bound Action? ...............................................................................................234
9.3 How You Can Call OData Actions .................................................................................235
9.4 How You Can Read Data from OData Services ............................................................241
9.4.1 Retrieving a Single OData Entity ...................................................................................241
9.4.2 Retrieving All Entities from an OData EntitySet .............................................................242
9.4.3 Retrieving Specific Entities from an OData EntitySet ....................................................242
9.4.4 Retrieve the Number of Entities from an OData EntitySet .............................................242
9.4.5 Known Limitations ..........................................................................................................243
10.2.3 Case 2 – Posting Messages from the Embedded Application to the Host Analytic
Application......................................................................................................................247
Figures
Figure 1: Bookmark Component in Outline ..................................................................................16
Figure 2: Side Panel of Bookmark Component ............................................................................16
Figure 3: Turn on Translation .......................................................................................................17
Figure 4: Export to PDF Component in Outline ...........................................................................18
Figure 5: Side Panel of Export to PDF Component .....................................................................18
Figure 6: Side Panel of Export to PDF Component to Configure the Settings ............................19
Figure 7: Create a Story from a Widget .......................................................................................21
Figure 8: Create Application .........................................................................................................23
Figure 9: Edit Sharing Settings ....................................................................................................23
Figure 10: Open in View Mode .....................................................................................................24
Figure 11: Run Analytic Application .............................................................................................25
Figure 12: Fullscreen....................................................................................................................25
Figure 13: Outline .........................................................................................................................27
Figure 14: Context Menu for Scripting Objects in Outline ............................................................27
Figure 15: Context Menu for Canvas Objects in Outline ..............................................................28
Figure 16: Widget Name ..............................................................................................................28
Figure 17: Analytics Designer Properties .....................................................................................29
Figure 18: Dropdown Menu Style .................................................................................................29
Figure 19: Filter Menu Style .........................................................................................................29
Figure 20: Visual Feedback of Mouse Click & Hover ...................................................................30
Figure 21: Settings of Icon ...........................................................................................................30
Figure 22: Type of Button .............................................................................................................30
Figure 23: Actions Menu ..............................................................................................................30
Figure 24: Quick Menu Options in Styling Panel .........................................................................31
Figure 25: Create Calculation ......................................................................................................34
Figure 26: Reference Script Variable ...........................................................................................34
Figure 27: Edit Scripts ..................................................................................................................37
Figure 28: Multiple Events ............................................................................................................37
Figure 29: Script for Dropdown ....................................................................................................37
Figure 30: Script for Chart ............................................................................................................37
Figure 31: Hover Menu.................................................................................................................37
Figure 32: Add Script Object ........................................................................................................38
Figure 33: Add Script Function .....................................................................................................38
Figure 34: Script Object Function .................................................................................................38
Figure 35: Script of Script Object Function ..................................................................................39
Figure 36: Script Editor.................................................................................................................39
Figure 37: 3 Areas of Script Editor ...............................................................................................39
Figure 38: Accessing Objects ......................................................................................................41
Figure 39 Gross Margin per Location Chart .................................................................................63
Figure 40 Newly Added Row Has Description "Sum", ID Is a UUID ............................................65
Figure 41 Totals Member Is Generated by Choosing Show Totals .............................................66
Figure 42 Comment Row or Comment Column Is Added to Table in Frontend ..........................67
Figure 43 Input Parameter Is Not a Concrete Data Cell Selection ..............................................70
Figure 44 Time Series Chart with Forecast Enabled ...................................................................74
Figure 45 Bubble Chart with Smart Grouping Enabled ................................................................76
Figure 46 Identify a Table Cell and Return a Result Member ......................................................79
Figure 47 Return "undefined" If More Than One Result Set Member Found ..............................80
Figures 8
Figure 39: Prompt Dialog: Variable Values Are Applied to the Widget Only ...............................82
Figure 40: Variable Values Are Applied to the Model of the Application or the Widget ...............82
Figure 41: Layout Section in the Styling Panel ............................................................................90
Figure 42: Example Application Switch Chart Table ....................................................................97
Figure 43: Switch Chart Table ......................................................................................................97
Figure 44: Example Application Dropdown ................................................................................101
Figure 45: Dropdown Selection ..................................................................................................102
Figure 46: Example Application Multi Selection .........................................................................109
Figure 47: Choose Input Data for Filtering R Visualization ........................................................119
Figure 48: Example Application Filter Line.................................................................................119
Figure 49: Select Filter Line .......................................................................................................120
Figure 50: Example Application Cascading Filtering .................................................................124
Figure 51: Add and Remove Dimensions ..................................................................................132
Figure 52: Example Application Settings Panel .........................................................................153
Figure 53: Popup Settings Panel ...............................................................................................153
Figure 54: Example Application Details Popup ..........................................................................171
Figure 55: Details Popup ............................................................................................................172
Figure 56: Example Application Word Cloud .............................................................................193
Figure 57: Toolbar Planning Features ........................................................................................215
Figure 58: Planning Enabled ......................................................................................................216
Figure 59: Unbooked Data .........................................................................................................216
Figure 60: SetUserInput .............................................................................................................217
Figure 61: Publish Version .........................................................................................................219
Figure 62: Publish Data ..............................................................................................................219
Figure 63: Success Message .....................................................................................................219
Figure 64: Message....................................................................................................................220
Figure 65: Dirty Version..............................................................................................................220
Figure 66: Planning Table in Popup ...........................................................................................221
Figure 67: Enabling Data Locking in the Model Preferences .....................................................222
Figure 68: Automatic Forecast ...................................................................................................225
Figure 69: Linear Regression .....................................................................................................226
Figure 70: Time Series Chart: Select the Interested Data Point ................................................226
Figure 71: Side Panel of Smart Insights.....................................................................................227
Figure 72: Smart Grouping .........................................................................................................227
Figure 73: Configure Smart Grouping in Builder Panel of Chart ................................................228
Figure 74: Configure Smart Grouping in Chart Details ..............................................................228
Figure 75: Smart Discovery Setting Panel .................................................................................229
Figure 76: New Document Created by Smart Discovery ...........................................................229
Figure 79: Create a SearchToInsight Component .....................................................................230
Figure 80: Launch Search To Insight .........................................................................................230
Figure 90 Search To Insight Example ........................................................................................231
Figure 81: OData Service in Outline ..........................................................................................235
Figure 82: OData Service ...........................................................................................................235
Figure 83: Actions for OData Service in Outline ........................................................................235
Figure 84: OData Service Side Panel ........................................................................................236
Figure 85: Define OData Service Properties ..............................................................................237
Figure 86: Styling Options ..........................................................................................................237
Figure 87: Widget Context Menu ...............................................................................................238
Figure 88: Create Script .............................................................................................................238
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 12
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 13
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 14
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.
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 19
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 20
setHeaderVisible(true);
isHeaderVisible();
setFooterText(“Page Footer”);
getFooterText();
setFooterVisible(true);
isFooterVisible();
setPageOrientation([Link]);
getPageOrientation();
setDateLocation([Link]);
getDateLocation();
setPageNumberLocation([Link]);
getPageNumberLocation();
setMetadataLocation([Link]);
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:
"[[Link]:M010_10_Accounts].[parentId].&[A134000]",
[Link]:M010_10_Operating_Income_Version: "[Link]"}, "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:
"[[Link]:M010_10_Accounts].[parentId].&[A134000]",
[Link]:M010_10_Operating_Income_Version: "[Link]"});
Getting Started 21
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:
"[[Link]:M010_10_Accounts].[parentId].&[A134000]",
[Link]:M010_10_Operating_Income_Version: "[Link]"});
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.
[Link]();
[Link](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.
[Link]("story_uuid", "page_uuid",
[[Link]("p_script_var_1", "123"),
[Link]("p_script_var_2", "Value with Spaces")]);
[Link]("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",
[Link]("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.
[Link]("myconnection", "mydataSourceName",
[Link]("P_script_var_1", "123"), true);
Designing an Analytic Application 23
3.1 Creating
To create an analytic application, you need the Application Creator role (or a custom role with the
CRUD permissions) to be able to see the menu entry in the Home menu under Create.
3.2 Browsing
Select Browse under the menu to access the file repository where are:
• Filters
• All existing public analytic applications
• Private applications
• Applications shared with you.
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 25
The analytic application opens in present mode by default when running the application from the
design time.
• Insert allows you to insert chart, table and all other available widgets.
• With Tools you can do chart scaling and create conditional formatting.
• Data contains refresh data and edit prompts.
• Designer opens the builder and styling panel.
• Run Analytics Application opens the application in another browser tab in present mode.
Present mode means, that the toolbar is visible only at hover. But it can be toggled to
View mode with a static toolbar by clicking on Fullscreen button in the toolbar.
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.
Designing an Analytic Application 27
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.
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:
Designing an Analytic Application 30
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.
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.
Designing an Analytic Application 31
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.
4.2.3.1Application Events
The application has two events: one that fires when the app starts, and another that is triggered
in certain embedded scenarios.
• onInitialization: This event runs once when the application is instantiated by a user. It
is where you script anything that you want to be done during startup. Like most events, it
has no input parameters.
Scripting in Analytics Designer 33
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 34
4.2.7 Timer
The Timer object 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.
Scripting in Analytics Designer 35
4.2.7.1Script APIs
Timer_1.start(delayInSeconds: number): void
Timer_1.stop(): void
Timer_1.isRunning(): boolean
Timer_1.onTimeout // event
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.
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.
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.
Scripting in Analytics Designer 39
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 40
Find a list of keyboard shortcuts in the help page “Using Keyboard Shortcuts in the Script Editor”:
[Link]
US/[Link].
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 41
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.
4.4.7.1for
for loops are standard JavaScript for loops, with one caveat. You must explicitly declare the for
iterator. This is valid JavaScript, but it isn’t accepted in the script editor:
for (i = 0; i < 3; i++) {
[Link]("Hello for, " + [Link]());
}
Instead, explicitly declare i. The example below is valid:
Scripting in Analytics Designer 43
4.4.7.2while
We fully support while loops in SAP Analytics Cloud Analytics Designer:
var nth = 1;
while (nth < 3) {
[Link]("Hello while, " + [Link]());
nth++;
}
4.4.7.3for in
An additional type of look is the for in iterator. Suppose you had a JavaScript object: you can
iterate over the properties with the for in loop. Data selections are JavaScript objects and can
be iterated over:
var selection = {
"Color": "red",
"Location": "GER"
};
for (var propKey in selection) {
var propValue = selection[propKey];
...
};
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.
4.4.10 this
The this keyword allows you to ignore the name of the object. It is simply the object that this
script is attached to, regardless of what it is called. It doesn’t matter and is merely a stylistic
choice. With this, refer to
• The instance itself within widget scripts or script object functions
• The parent instance explicitly by its variable name, such as Chart_1
• The parent instance as this
When performing the above console print on one of the events of Chart_1 itself, use the following
variation of the code:
var theDataSource = [Link]();
[Link]([Link]());
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.[Link], 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 46
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 [Link].
• 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 47
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.[Link].
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.[Link].
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 48
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 = [Link]();
[Link](theVariables);
4.5.1.1Exclude Filters
You can filter out members from the drill-down with exclude filters. The following examples show
the use of exclude filters:
Scripting in Analytics Designer 49
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});
4.5.1.2Range Filters
You can filter ranges of members in the drill-down with range filters.
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 50
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"}]);
getDimensionProperties
getDimensionProperties(dimension: string | DimensionInfo): DimensionPropertyInfo[]
Returns all available dimension properties of the specified dimension of a data source.
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:
[Link](Chart_1.getDataSource().getVariables());
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 = [Link]().getNumber("gmCorrelation");
var sCor = [Link]();
[Link]("Margin Correlation: " + sCor);
Scripting in Analytics Designer 52
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 53
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:
[Link]
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.
[Link]
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.
getDimensionOnRows
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 [Link]() to get the value of a cell. See also the documentation of Selection
([Link]
US/doc/[Link]).
Widget Concepts, APIs, and Usages 58
getSelections(): Selection[]
Returns the selections of the chart. You can use the elements of the returned array with the
function [Link]() to get the value of a cell. See also the documentation of Selection
([Link]
US/doc/[Link]).
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");
5.6.2.1Compact Display
You can control the compact display (formerly called Universal Display Hierarchy) of a table.
Note: This API is available on Table widgets and is applicable to 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.
5.6.2.2Zero Suppression
You can control the zero suppression of values of a table.
Note: This API is available on Table widgets and is applicable to 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.
5.6.2.3Dimension Properties
You can control the active (visible) dimension properties of a table.
Widget Concepts, APIs, and Usages 59
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.
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", [Link]);
addMeasure
addMeasure(measure: string|Measure, feed: Feed, position?: integer): void
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.
Widget Concepts, APIs, and Usages 60
Example:
Chart_1.addMeasure("[Account_BestRunJ_sold].[parentId].&[Gross_MarginPlan]",[Link]
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([Link]);
getSelections
getSelections(): Selection[]
Returns the selections of the chart. You can use elements of the returned array with the function
[Link]() to get the value of a cell. See also the documentation of Selection
([Link]
US/doc/[Link]).
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", [Link]);
removeMeasure
removeMeasure(measure: string|Measure, feed: Feed): void
Removes the measure from the feed.
Widget Concepts, APIs, and Usages 61
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.
Before these APIs had been introduced, you could retrieve individual data cells using
[Link](). However, it was not possible to retrieve all members for a dimension in a
specific result set.
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.
Widget Concepts, APIs, and Usages 62
ResultSet {
[key: string]: DataContext;
}
Selection {
[key: string]: string;
}
SelectionContext {
[key: string]: [string];
}
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.
Widget Concepts, APIs, and Usages 63
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",
"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"
Widget Concepts, APIs, and Usages 64
}
}, {
"@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",
"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"
}
Widget Concepts, APIs, and Usages 65
}, {
"@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.
Example 3: Newly added row has the description “Sum” and its ID is a UUID
Table_1.getDataSource().getResultSet();
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"formattedValue": " 235.04",
"rawValue": " 235036949.37"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"description": "California"
}
}, {
...
}, {
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"description": "Gross Margin",
"formattedValue": "48.30",
"rawValue": "48301721.3"
},
"Location_4nm2e04531": {
"id": "30835424-2216-4348-9273-946191519134", // generated in frontend
"description": "Sum"
}
}]
Table_1.getDataSource().getResultSet();
In the below example, a comment column is added to a table and one comment cell is input with
text.
Table_1.getDataSource().getResultSet();
// ResultSet[]
[{
"Version": {
Widget Concepts, APIs, and Usages 68
"id": "[Link]",
"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"
}
}, {
...
}]
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.
"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]"
}
}]
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]"
}, {
"@MeasureDimension": "[Account_BestRunJ_sold].[parentId].&[Gross_Margin]",
"Location_4nm2e04531":
"[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[CT2]"
}]);
"parentId": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]"
}
}]
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.
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"
Widget Concepts, APIs, and Usages 72
},
"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]",
"description": " Carbonated Drinks "
}
}, {
...
}]
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.
"@MeasureDimension": {
"id": "[Account_BestRunJ_sold].[parentId].&[Discount]",
"description": "Discount",
"rawValue": "30720120.73",
"formattedValue" "30.72"
},
"Location_4nm2e04531": {
"id": "[Location_4nm2e04531].[State_47acc246_4m5x6u3k6s].&[SA1]",
"description": "California"
},
"Product_3e315003an": {
"id": "[Product_3e315003an].[Product_Catego_3o3x5e06y2].&[PC4]",
"description": "Alcohol"
}
}]
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.
Widget Concepts, APIs, and Usages 74
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"
},
"@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"
Widget Concepts, APIs, and Usages 75
},
"@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"
}
}, {
"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"
}
}]
Widget Concepts, APIs, and Usages 76
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",
"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]",
Widget Concepts, APIs, and Usages 77
"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"
}
}, {
...
}]
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 78
}]
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 79
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 80
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 47 Return "undefined" If More Than One Result Set Member Found
The widget should be a chart or table. Currently R visualization, Geo, and custom widgets are not
supported.
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();
[Link]([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();
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 < [Link]; i++) {
[Link](aVariables[i].id);
}
Widget Concepts, APIs, and Usages 82
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 48). 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 49).
Figure 48: Prompt Dialog: Variable Values Are Applied to the Widget Only
Figure 49: 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.
Known limitation: Setting variable values of hierarchy node variables is not supported yet.
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"]});
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"]});
[Link] 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"});
[Link] 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"});
Note: If you remove a variable value from a mandatory variable, then this operation is ignored.
Widget Concepts, APIs, and Usages 84
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.
Widget Concepts, APIs, and Usages 85
close
close(): void
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 86
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","[Link]
xml");
RssReader_Content.setSelectedFeed("[Link]
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:
[Link]().setString("titleParam", "Gross Margin of
Oregon");
Example:
Calculate the total of gross margin in RVisualization script, and return the result:
[Link]().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
[Link]("BestRunJuice_SampleModel").getDataSource().setDimensio
nFilter("Location_4nm2e04531", ["CT13", "CT14", "CT15", "CT16", "CT17", "CT18"]);
Widget Concepts, APIs, and Usages 88
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();
[Link](): Unit; // Returns the top margin between the widget that you define
layout for and the widget's parent container.
[Link](value: Unit); // Sets the top margin between the widget that you
define layout for and the widget's parent container.
[Link](): Unit; // Returns the bottom margin between the widget that you
define layout for and the widget's parent container.
[Link](value: Unit); // Sets the bottom margin between the widget that
you define layout for and the widget's parent container.
[Link](): Unit; // Returns the width of the widget that you define layout
for.
[Link](value: Unit); // Sets the width of the widget that you define
layout for.
[Link](): Unit; // Returns the height of the widget that you define
layout for.
[Link](value: Unit); // Sets the height of the widget that you define
layout for.
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.
Widget Concepts, APIs, and Usages 90
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.
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([Link](98,
[Link]));
Panel_2.getLayout().setBottom([Link]);
Panel_2.getLayout().setHeight([Link](376,
[Link]));
Panel_3.getLayout().setBottom([Link]);
Panel_3.getLayout().setLeft([Link](1,
[Link]));
Widget Concepts, APIs, and Usages 91
Panel_3.getLayout().setTop([Link](476,
[Link]));
if (screenWidth < 500) {
//one column
Panel_3.getLayout().setHeight([Link](
(baseChartHeight + padding) * 4 + padding * 3 +
Table_1.getLayout().getHeight().value, [Link]));
} else {
//two columns
Panel_3.getLayout().setHeight([Link](840,
[Link]));
}
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 [Link](), 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:
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:
Widget Concepts, APIs, and Usages 92
[Link]
/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
[Link](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.
Widget Concepts, APIs, and Usages 93
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 94
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.
Typical Patterns and Best Practices 97
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
[Link](true);
[Link](false);
Switch_to_Table_display.setVisible(true);
Switch_to_Chart_display.setVisible(false);
on the button.
[Link](false);
[Link](true);
Switch_to_Table_display.setVisible(false);
Switch_to_Chart_display.setVisible(true);
Typical Patterns and Best Practices 101
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 102
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 105
[Link]().setDimensionFilter("Account_BestRunJ_so
ld",selectedId);
[Link](selectedId, [Link]);
if ([Link] > 0) {
for (var i = 0; i < [Link]; i++){
// Measure
Dropdown_Measures.addItem(measures[i].id,
measures[i].description);
if (selectedKey === "" && i === 0) {
selectedKey = measures[i].id;
Dropdown_Measures.setSelectedKey(selectedKey);
[Link](["selectedKey ", selectedKey]);
}
[Link](["CurrentMeasure ", measures]);
}
}
[Link](selectedKey);
Typical Patterns and Best Practices 108
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 109
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.
[Link](CurrentMeasureFilterSelection[i]
, [Link]);
}
}
// add Measures
[Link]().setDimensionFilter("Account_Be
stRunJ_sold",selectedIds);
for (i = 0; i < [Link]; i++) {
[Link](selectedIds[i], [Link]);
}
// save the current selection into global variable
CurrentMeasureFilterSelection = selectedIds;
similarly select .
[Link](CheckboxGroup_Measures.getSel
ectedKeys());
Typical Patterns and Best Practices 116
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
[Link](AllMeasures);
if ([Link] > 0) {
for (var i = 0; i < [Link]; i++) {
// add the Measure to checkbox group
CheckboxGroup_Measures.addItem(measures[i].id,measur
es[i].description);
//add the measure to the selecedKeys
[Link](measures[i].id);
CheckboxGroup_Measures.setSelectedKeys(selectedKeys)
;
[Link](["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 119
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 120
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).
[Link]().copyDimensionFilterFrom([Link]
rce(), "Location_4nm2e04531");
[Link]().copyDimensionFilterFrom([Link]
rce(), "Product_3e315003an");
[Link]().copyDimensionFilterFrom([Link]
rce(), "Sales_Manager__5w3m5d06b5");
[Link]().copyDimensionFilterFrom([Link]
rce(), "Store_3z2g5g06m4.Store_GEOID");
Typical Patterns and Best Practices 123
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 125
Location_4nm2e04531 Location
Product_3e315003an Product
Store_3z2g5g06m4 Store
// Table
[Link](CurrentDimension);
[Link](sel);
//Chart
[Link](CurrentDimension, [Link]);
[Link](sel, [Link]);
// loop
for (var i = 0; i < [Link]; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id, 'Flat
Presentation');
}
else {
Typical Patterns and Best Practices 129
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
[Link](['Hierarchy: ', hierarchy]);
[Link](['Current Dimension: ', CurrentDimension]);
// Table
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
// Chart
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
// loop
for (var i = 0; i < [Link]; 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
[Link](['Hierarchy: ', hierarchy]);
[Link](['Current Dimension: ', CurrentDimension]);
//Table
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 131
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 132
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 133
CheckboxGroup_Columns.removeAllItems();
CheckboxGroup_Rows.removeAllItems();
CheckboxGroup_Free.removeAllItems();
CurrentDimensionColumn = [Link]([Link]);
CurrentDimensionRows = [Link]([Link]);
[Link](["CurrentDimensionColumn should empty",
[Link]()]);
[Link](["CurrentDimensionRows should empty",
[Link]()]);
// Dimension in Columns
var dimCol = [Link]();
if ([Link] > 0) {
for (var i = 0; i < [Link]; i++) {
[Link](dimCol[i].id);
[Link](["CurrentDimensionColumn ",
dimCol[i].id]);
}
}
Typical Patterns and Best Practices 146
// Dimension in Rows
var dimRows = [Link]();
if ([Link] > 0) {
for (i = 0; i < [Link]; i++) {
[Link](dimRows[i].id);
[Link](["CurrentDimensionRows ",
dimRows[i].id]);
}
}
CheckboxGroup_AllDimensions.setSelectedKeys([AllDimension
s[i]]);
var dimdesc =
CheckboxGroup_AllDimensions.getSelectedTexts();
CheckboxGroup_Free.addItem(AllDimensions[i],
dimdesc[0]);
[Link](["AllDimensions",AllDimensions[i],
dimdesc[0]]);
}
}
}
[Link](["CurrentDimensionColumn",
CurrentDimensionColumn]);
[Link](["CurrentDimensionRows",
CurrentDimensionRows]);
CheckboxGroup_Free.setSelectedKeys([CurrentDimensionRows[
i]]);
dimdesc = CheckboxGroup_Free.getSelectedTexts();
CheckboxGroup_Rows.addItem(CurrentDimensionRows[i],
dimdesc[0]);
CheckboxGroup_Free.removeItem(CurrentDimensionRows[i]);
}
}
}
if ([Link] > 0) {
for (i = 0; i < [Link]; 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 147
[Link](CheckboxGroup_Measures.getSelected
Keys());
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
[Link](AllMeasures);
[Link]();
[Link]();
Typical Patterns and Best Practices 149
[Link]();
[Link](selectedKeys);
[Link]();
Typical Patterns and Best Practices 151
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 153
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 154
There, enter
“Dropdown_MeasureGroup” as the
Name.
Typical Patterns and Best Practices 155
Actual Actual
Plan Plan
_Abs Absolute
_Percent % Deviation
Popup_Settings.open();
[Link]().setDimensionFilter("Account_Bes
tRunJ_sold", selectedId);
[Link](selectedId, [Link]);
Typical Patterns and Best Practices 165
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginActual]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginPlan]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Abs]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Percent]", [Link]);
}
else if (CurrentMeasureGroup === 'Discount') {
[Link]("[Account_BestRunJ_sold].[parentI
d].&[DiscountActual]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[DiscountPlan]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Discount_Abs]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Discount_Percent]", [Link]);
}
else if (CurrentMeasureGroup === 'Quantity_Sold') {
Typical Patterns and Best Practices 166
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldActual]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldPlan]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Abs]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Percent]", [Link]);
}
else if (CurrentMeasureGroup ===
'Original_Sales_Price') {
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PriceActual]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PricePlan]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Abs]", [Link]);
[Link]("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Percent]", [Link]);
}
[Link](CurrentMeasureFilterSelectionPopu
p[i], [Link]);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = [Link]([Link]);
CurrentMeasureSelection = Selected_Measures;
[Link](CurrentMeasureFilterSelectionPopu
p[i], [Link]);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = [Link]([Link]);
[Link]().removeDimensionFilter("Account_
BestRunJ_sold");
[Link]().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 172
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 < [Link]; 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
[Link](['Hierarchy: ', hierarchy]);
[Link](['Current Dimension: ',
CurrentDimension]);
Details_Chart.removeMeasure(CurrentMeasures[i],
[Link]);
Details_Chart.addMeasure(memberId,
[Link]);
}
//Details_Chart.addMeasure(memberId,
[Link]);
[Link](memberId);
Typical Patterns and Best Practices 184
Popup_show = true;
}
// Dimension
else {
[Link](['Selection Dimension: ',
dimensionId]);
[Link](['Selection Member: ', memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
if (Popup_show === true) {
Popup_Details.open();
}
if ([Link] > 0) {
Details_Chart.getDataSource().removeDimensionFilter(C
urrentDimension);
Details_Chart.addMeasure(memberId,
[Link]);
[Link](memberId);
Popup_show = true;
}
Typical Patterns and Best Practices 186
// Dimension
else {
[Link](['Selection Dimension: ',
dimensionId]);
[Link](['Selection Member: ',
memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
}
Details_Chart.removeMeasure(CurrentDetailsMeasures[i]
, [Link]);
}
CurrentDetailsMeasures =
[Link]([Link]);
// loop
for (var i = 0; i < [Link]; 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
[Link](['Hierarchy: ', hierarchy]);
[Link](['Current Dimension: ',
CurrentDimension]);
//Table
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
[Link]().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 189
//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 195
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),
[Link]=0.2, colors=[Link](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),
[Link]=0.2, colors=[Link](8, myColor))
if ([Link] > 0) {
var selection = sel[0];
[Link](['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 211
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 212
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 ([Link] !== 0) {
for (var i = 0; i < [Link]; i++) {
[Link](['List Dimension: ', i ,
list[i].displayId]);
[Link](['List Description: ', i ,
list[i].description]);
[Link](['List Member: ', i , list[i].id]);
Hidden_DropDown_Customer.addItem(list[i].id,
list[i].description);
}
}
Typical Patterns and Best Practices 213
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({"[Link]:Account":
"[[Link]:Account].[parentId].&[TAXES]", "[Link]:ProfitAndLoss_Version02":
"[Link]"}, "*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 214
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.
[Link](): 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 216
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 221
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
• [Link]().getDataLocking()
• [Link]().[Link]()
• [Link]().[Link]()
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();
[Link]([Link]());
Note that you can also check if a model is data locking enabled in SAP Analytic Cloud by checking
the model preferences (see Figure 76).
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 223
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 [Link], 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,
[Link]);
Planning 224
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.
Predictive 225
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 226
Figure 79: Time Series Chart: Select the Interested Data Point
Predictive 227
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 = [Link]("Product_3e315003an");
var SDsetting = [Link](ds, "Product_3e315003an",
[members[1]]);
[Link](["Location_4nm2e04531", "Store_3z2g5g06m4"]);
Predictive 229
[Link](["[Account_BestRunJ_sold].[parentId].&[Gross_Margin]"
, "[Account_BestRunJ_sold].[parentId].&[Discount]"]);
[Link](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 = [Link];
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 = [Link];
if (CheckboxGroup_1.getSelectedKeys().length !== 0) {
mode = [Link];
}
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 232
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 233
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: [Link]
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 235
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 236
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 237
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 240
var totalnumberofseats =
[Link]([Link][0].Totalnumberofseats);
var currency = [Link][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 242
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 243
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 245
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
[Link]
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();
[Link]([Link], message,
"[Link]
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 == "[Link] {
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 248
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.
13 Important Links
Please open the SAP Help page to find many more information about SAP Analytics Cloud,
analytics designer:
[Link]
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
[Link]/copyright for additional trademark information and notices.