Developer Handbook Sac Analytics Designer
Developer Handbook Sac Analytics Designer
Developer Handbook
Table of Contents
Table of Contents.................................................................................................................... 1
Figures..................................................................................................................................... 6
Preface..................................................................................................................................... 8
6.2 Selecting Measures via Dropdown or Radio Button to Filter Table and Chart to
Display (Single Selection) ............................................................................................ 72
6.3 Selecting Measures via Dropdown to Filter Table and Chart to Display (Multi-
Selection) .................................................................................................................... 79
6.4 Using Filter Line for Filtering Table, Chart, and R Visualization .................................... 89
6.5 Cascaded Filtering ...................................................................................................... 95
6.6 Add and Remove Dimension in Rows and Columns for Table .................................... 102
6.7 Creating a Settings Panel Using a Popup Window ..................................................... 123
6.8 Selection Handling in a Table or Chart and Open a Details Popup ............................. 142
6.9 Using R Widget Word Cloud for Visualization ............................................................ 164
6.10 Set User Input for Planning Data ............................................................................... 184
7 Planning................................................................................................................... 186
7.1 What to Expect from Analytics Designer Regarding Planning? ................................... 186
7.2 Basic Planning Concepts in Analytics Designer ......................................................... 186
7.3 Refreshing Your Data ................................................................................................ 188
7.4 Set User Input ........................................................................................................... 188
7.5 Planning Versions ..................................................................................................... 189
7.5.1 Private Versions ........................................................................................................ 189
7.5.2 Public Versions ......................................................................................................... 189
7.6 How to Manage Versions........................................................................................... 190
7.6.1 Publishing and Reverting Data Changes.................................................................... 190
7.6.2 Copy ......................................................................................................................... 192
7.7 Data Locking ............................................................................................................. 192
7.7.1 Using getDataLocking() ............................................................................................. 193
7.7.2 Using getState() ........................................................................................................ 193
7.7.3 Using setState() ........................................................................................................ 194
8 Predictive................................................................................................................. 196
8.1 Time Series Forecast ................................................................................................ 196
8.1.1 Switch On and Off Forecast ....................................................................................... 196
8.1.2 Configure Forecast .................................................................................................... 196
8.2 Smart Insights ........................................................................................................... 197
8.2.1 Discover per Selected Data Point .............................................................................. 197
8.3 Smart Grouping ......................................................................................................... 198
8.3.1 Switch On and Off Smart Grouping ............................................................................ 198
8.3.2 Configure Smart Grouping ......................................................................................... 199
8.4 Smart Discovery ........................................................................................................ 199
8.5 Search To Insight ...................................................................................................... 200
Figures
Figure 1: Bookmark Component in Outline .............................................................................. 15
Figure 2: Side Panel of Bookmark Component ........................................................................ 15
Figure 3: Turn on Translation .................................................................................................. 16
Figure 4: Export to PDF Component in Outline ........................................................................ 17
Figure 5: Side Panel of Export to PDF Component .................................................................. 17
Figure 6: Side Panel of Export to PDF Component to Configure the Settings ........................... 18
Figure 7: Create a Story from a Widget ................................................................................... 20
Figure 8: Create Application .................................................................................................... 22
Figure 9: Edit Sharing Settings ................................................................................................ 22
Figure 10: Open in View Mode ................................................................................................ 23
Figure 11: Run Analytic Application ......................................................................................... 24
Figure 12: Fullscreen .............................................................................................................. 24
Figure 13: Outline ................................................................................................................... 25
Figure 14: Context Menu for Scripting Objects in Outline ......................................................... 26
Figure 15: Context Menu for Canvas Objects in Outline ........................................................... 26
Figure 16: Widget Name ......................................................................................................... 27
Figure 17: Analytics Designer Properties ................................................................................. 27
Figure 18: Dropdown Menu Style ............................................................................................ 28
Figure 19: Filter Menu Style .................................................................................................... 28
Figure 20: Visual Feedback of Mouse Click & Hover................................................................ 28
Figure 21: Settings of Icon....................................................................................................... 28
Figure 22: Type of Button ........................................................................................................ 28
Figure 23: Actions Menu ......................................................................................................... 29
Figure 24: Quick Menu Options in Styling Panel ...................................................................... 29
Figure 25: Create Calculation .................................................................................................. 32
Figure 26: Reference Script Variable ....................................................................................... 32
Figure 27: Edit Scripts ............................................................................................................. 35
Figure 28: Multiple Events ....................................................................................................... 35
Figure 29: Script for Dropdown ................................................................................................ 35
Figure 30: Script for Chart ....................................................................................................... 35
Figure 31: Hover Menu............................................................................................................ 36
Figure 32: Add Script Object ................................................................................................... 36
Figure 33: Add Script Function ................................................................................................ 36
Figure 34: Script Object Function ............................................................................................ 36
Figure 35: Script of Script Object Function............................................................................... 37
Figure 36: Script Editor............................................................................................................ 37
Figure 37: 3 Areas of Script Editor ........................................................................................... 37
Figure 38: Accessing Objects .................................................................................................. 39
Figure 39: Prompt Dialog: Variable Values Are Applied to the Widget Only .............................. 58
Figure 40: Variable Values Are Applied to the Model of the Application or the Widget .............. 58
Figure 41: Layout Section in the Styling Panel ......................................................................... 66
Figure 42: Example Application Switch Chart Table ................................................................. 68
Figure 43: Switch Chart Table ................................................................................................. 68
Figure 44: Example Application Dropdown .............................................................................. 72
Figure 45: Dropdown Selection ............................................................................................... 73
Figure 46: Example Application Multi Selection ....................................................................... 80
Figure 47: Choose Input Data for Filtering R Visualization ....................................................... 90
Figures 7
Preface
Why shall you read this book? Because we offer you the following:
We give you a kickstart in how to use the SAP Analytics Cloud, analytics designer. We offer you
coding examples and we want to get you enthusiastic about the enormous flexibility you have for
building advanced analytic applications. We want you to become a fan of our product seeking for
the unlimited possibilities in the cloud.
Thanks to all people around the globe who helped writing this first version of the developer
handbook for SAP Analytics Cloud, analytics designer!
Thanks to all developers, as well as colleagues from quality team, user experience, user
assistance and product management (and any other contributor) who made this awesome product
possible!
About Analytics Designer 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 life-cycle. 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 11
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 12
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 13
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 life cycle 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 18
The settings can be configured both at design time and run time. Application designers can update
the values via the side panel of Export to PDF at design time. While at run time, 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 19
setHeaderVisible(true);
isHeaderVisible();
setFooterText(“Page Footer”);
getFooterText();
setFooterVisible(true);
isFooterVisible();
setPageOrientation(PageOrientation.Portrait);
getPageOrientation();
setDateLocation(PageDateLocation.Header);
getDateLocation();
setPageNumberLocation(PageNumberLocation.Header);
getPageNumberLocation();
setMetadataLocation(PageMetadataLocation.Header);
getMetadataLocation();
setExportInBackgroundEnabled(true);
isExportInBackgroundEnabled();
Manage Comment
Data cell-based comments can be managed via APIs by specifying data context or comment ID.
// Add comment to table cell
Table_1.getDataSource().getComments().addComment({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"}, "comment1");
// Remove comment by context. One data cell has only one comment
// thread. In this case, all comments belong to this thread will
// be removed.
Table_1.getDataSource().getComments().removeComments({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"});
Getting Started 20
Get Comment
Besides posting or removing comments, the application designer can read the comment
information by data context or comment ID. The comment information includes content, author,
creation date and so on.
// If comment ID is specified, the related comment is returned
var oCommentInfo2 = Table_1.getDataSource().getComments().getComment("28760729-
2540-4227-b016-428450515042");
// Get comment thread by context
var aCommentInfos =
Table_1.getDataSource().getComments().getAllComments({@MeasureDimension:
"[sap.epm:M010_10_Accounts].[parentId].&[A134000]",
sap.epm:M010_10_Operating_Income_Version: "public.Actual"});
Be able to turn on and off comment display via APIs. Once the comment mode is disabled, the
comments and related UI will be invisible at runtime.
Application.isCommentModeEnabled();
Application.setCommentModeEnabled(true);
Like a Comment
Whether to like a comment or not can be configured via API as well. Once a comment id is
specified, the number of like of the related comment will be updated.
setCommentLiked(("28760729-2540-4227-b016-428450515042", true);
The new story will be created in a new browser page, and the settings and data state (that is,
filter, and so on) will be carried over as well.
Basically, the APIs can be used in two ways: open the analytic application or a page of a story
directly or open an URL.
The APIs take the uuid of an analytic application or a page in a story and open the expected
application or page in a new tab if parameter “newTab” is set to true.
NavigationUtils.openStory("story_uuid", "page_uuid",
[UrlParameter.create("p_script_var_1", "123"),
UrlParameter.create("p_script_var_2", "Value with Spaces")]);
NavigationUtils.openApplication("application_uuid", true);
Open URL
The user can also choose to open an URL, which is a story or analytic application URL, or even
a general external URL. The URL can be opened in a new tab or in a browser page that is already
open.
var storyURL = createStoryUrl("story_uuid", "page_uuid",
UrlParameter.create("p_script_var_1", "123"));
var appURL = createApplicationUrl("application_uuid");
openUrl(storyURL, true);
openUrl(appURL, true);
The user can also choose to open a data analyzer to analyze data of a data source. The user can
pass the name of the connection, the name of the data source, and URL parameters, if necessary.
The data analyzer opens in a new tab or in a browser page that is already open.
NavigationUtils.openDataAnalyzer("myconnection", "mydataSourceName",
UrlParameter.create("P_script_var_1", "123"), true);
Designing an Analytic Application 22
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. The analytic application opens in present mode by
default when running the application from the design time.
Designing an Analytic Application 24
Click on + to create Script Variables, Script Objects, OData Services, and Predictive Models. You
can maintain them here and use them in every script of the application.
The outline has a search bar that filters the complete tree to match your search. Click the symbol
> to expand or collapse an item.
The widgets in the outline, on the canvas, and the side panel are always synchronized and based
on your selection. Widgets in the outline have a context menu containing Rename, Find
Reference, Delete, and Hide. Hide conceals the widget on the canvas in edit mode. It has no
influence on the different view modes when executing the application.
Widgets have their own analytic application Properties section in the Styling panel. This is where
the widget name used for scripting can be changed; it is updated in the outline, and vice versa.
The specific properties of the analytics designer depend on the widget type.
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.
Designing an Analytic Application 28
In addition to the default style, users can now configure different styles of filter menu during mouse
hover or mouse down.
Button Widget
Several new settings of Button widget have been added in the Styling Panel:
The possible types of button are: standard, lite, emphasized, positive (accept), and negative
(reject).
Under Actions, you can flag the option to hide the widget in application view time.
Designing an Analytic Application 29
At runtime for each widget, there are quick menus for either a widget or relevant data points (that
is, Table or Chart). An application developer can configure the visibility of these quick menu items
via the settings in the Styling Panel of a widget. More styling options are available.
By checking or unchecking the checkbox before each item, the application developer can control
the availability of the related quick menu item at runtime.
Please be advised that the configurable items in quick menus vary by widget.
Most modern analytics tools avoid scripting to simplify the designer’s tasks. Users may find it
easier to use at first, but they quickly find themselves limited to the scenarios built into the tool.
Scripting allows you to go beyond present narratives, to respond to user interaction in a custom
way, to change data result sets, and to dynamically alter layout. Scripting frees your creativity.
For example, when calling an API method on a Business Warehouse DataSource, the code
completion can propose measures as code completion options or values to specify a filter.
4.2.3 Events
Scripts always run in response to something happening in the application. Application events are
your hook. There are several types of events in analytic applications. Some occur in the
application itself and some occur on individual widgets.
• 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.
• onPostMessageRecieved: If your application is embedded in an iFrame, your SAP Analytics
Cloud analytic application can communicate bidirectionally with the host web app using
JavaScript PostMessage (see also: https://developer.mozilla.org/ en-
US/docs/Web/API/Window/postMessage) calls. It allows the host application to pass
information into the analytic application. This event is called whenever the host
application makes a post message call into the analytic application.
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 32
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 33
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.
Scripting in Analytics Designer 36
Within a script object, you can add several functions, by invoking Add Script Function in the
context menu. Keep in mind that the script object container is an organizational aid for you.
Individual functions are nested within global script objects. For example, in the figure below Error! R
eference source not found. you see the function1 nested within a script object called
ScriptObject_1.
Like canvas widgets, the scripts attached to a function are created by clicking the icon in the
hover menu of that function. Functions that have and don’t have scripts are visible in the outline,
just as with widgets.
Once you have a script attached to a function, you can call it whenever you please, from any
other script. The script objects are accessible by name and individual functions are accessible
within the objects. If you wanted to invoke the function1 script within ScriptObject_1, you would
call is like this:
ScriptObject_1.function1();
Write script in the main body using the inbuild help features like code completion and value help.
Scripting in Analytics Designer 38
Find a list of keyboard shortcuts in the help page “Using Keyboard Shortcuts in the Script Editor”:
https://help.sap.com/doc/00f68c2e08b941f081002fd3691d86a7/release/en-
US/68dfa2fd057c4d13ad2772825e83b491.html.
Find all places where a widget or a scripting object is used with the Find References feature. You
can find it in the context menu per object in the outline. The result is displayed in the Reference
list tab of the Info Panel.
You can change the name of a widget, gadget, script variable, script object, or script object
function by selecting it in the Outline, clicking the More button, selecting Rename, and entering a
new name.
You can change the name of a widget or gadget by selecting it in the Outline, then entering in the
Styling Panel a new name in the Name input field.
You can change the name of a script variable, script object, or script object function by selecting
it in the Outline, entering in the Styling Panel a new name in the Name input field, then clicking
button Done.
You can change the name of a script object function argument by selecting the script object
function in the Outline, clicking the Edit button of the function argument in the Styling Panel,
entering a new name in the Name input field, then clicking button Done.
4.4.1 Typing
Normal JavaScript is weakly typed and dynamically typed. Weak typing means that the script
writer can implicitly coerce variables to act like different types. For example, you could have an
integer value and treat it as if it were a string. Dynamic typing means that the runtime will try to
guess the type from the context at that moment and the user can even change the type after the
Scripting in Analytics Designer 39
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.
This would print “Hello World, 1” to the JavaScript console of the browser. Complex objects can
be printed.
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.1 for
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++) {
console.log("Hello for, " + nth.toString());
}
Instead, explicitly declare i. The example below is valid:
Scripting in Analytics Designer 41
4.4.7.2 while
We fully support while loops in SAP Analytics Cloud Analytics Designer:
var nth = 1;
while (nth < 3) {
console.log("Hello while, " + nth.toString());
nth++;
}
4.4.7.3 for 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.
}
This is false, and you can see the if statement is skipped:
var aNumber = 1;
if (aNumber === "1") {
...
}
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 = this.getDataSource();
console.log(theDataSource.getVariables());
Note: Analytics designer supports debugging analytics designer scripts in the Chrome browser
only.
Note: Analytics designer transforms the analytics designer scripts before they are run in the
browser. Thus, they will not look exactly like the script you wrote in the script editor of analytics
designer.
Note: To find the analytics designer script in the browser’s development tools, the script needs to
be run at least once during the current session.
Analytics designer script names follow a specific naming convention: All scripts of an application
are grouped in a folder <APPLICATION_NAME>. Each script is named
<WIDGET_NAME>.<FUNCTION_NAME>.js.
For example: If an application My Demo Application contains a button Button_1 with an onClick
handler, then the name of the script is Button_1.onClick.js, which is in folder
My_Demo_Application .
Note: Special characters, for example space characters in the application name are replaced by
an underscore (_), except minus (-) and dot (.) characters, which remain unchanged.
You can quickly find a script by its name with the following steps:
• Press F12 to open the browser’s development tools.
• Press CTRL+P, then start typing a part of the script’s name.
Scripting in Analytics Designer 44
You can also find a script in the file tree on the left side of the development tools using the
following steps:
• Press F12 to open the browser’s development tools.
• Select the tab Sources.
• Open the node whose name starts with sandbox.worker.main.
• Open the node named AnalyticApplication.
• Find the folder with your application’s name. The scripts that have already been executed
for the current analytic application appear in this folder.
To pause a script while it is being executed, you can set breakpoints at certain locations in the
analytic designer script.
Scripting in Analytics Designer 45
To set a breakpoint, open the script you want to pause during its execution and click on the line
number on the left side of the opened script in the developer tools.
A blue marker appears, highlighting the clicked line number. It indicates where the script will be
paused when it is being executed the next time. You can add several breakpoints in one script to
pause its execution at different points in time.
To remove a breakpoint, click on the blue marker. The blue maker disappears, and the script's
execution won't stop at this point when the script is run the next time.
Analytic designer supports more debugging features by running an analytic application in debug
mode.
You enable the debug mode for an analytic application by appending the string ;debug=true to
the URL of the analytic application in the browser.
Note: The analytic designer script names in the browser change when the analytic application is
run in debug mode. In debug mode, the suffix -dbg is added to the script name, for example,
Button_1.onClick-dbg.js.
You enable the debug mode for an analytic application by appending the string ;debug=true to
the URL of the analytic application in the browser.
Note: The analytic designer script names in the browser change when the analytic application is
run in debug mode. In debug mode, the suffix -dbg is added to the script name, for example,
Button_1.onClick-dbg.js.
When the debug mode is enabled, you can pause an analytics designer script at a specific
location while it is being executed by placing a debugger; statement at this location of the script.
The difference to a regular breakpoint is that you can define the location where the script is paused
already while writing the script itself, that is, before running it.
Scripting in Analytics Designer 46
When the debug mode is enabled, then comments in a script are preserved in the transformed
script that is executed in the browser. This makes it easier to recognize specifically commented
locations in a script when its execution in the browser is paused.
Example:
Let’s say you want to print the variables on Chart_1 to the console.
Get the data source on a widget with its getDataSource() function. This returns the data source
attached to that widget and allows you to perform further operations.
The snippet below prints the data source variables of Chart_1 to the console:
var theDataSource = Chart_1.getDataSource();
var theVariables = theDataSource.getVariables();
console.log(theVariables);
Suppose you were only logging the variables in the above example as a debug aid. You were not
re-using them, and the multiple lines were visual clutter. Then you might want to use method
chaining. The code below uses method chaining for compactness and does the same thing:
console.log(Chart_1.getDataSource().getVariables());
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.
Scripting in Analytics Designer 48
Reading
Suppose you had an R widget that had a very simple script. It just gets the correlation coefficient
between two measures on a model and puts that into a number named gmCorrelation:
grossMargin <- BestRun_Advanced$`Gross Margin`
grossMarginPlan <- BestRun_Advanced$`Gross Margin Plan`
gmCorrelation <- cor(grossMargin, grossMarginPlan)
Use the getEnvironmentValues on the R widget to access its environment and getNumber to read
a number from the R environment. The following JavaScript code takes the correlation coefficient
from the R environment and logs it to the JavaScript console. Note the this. This code was taken
from the onResultChanged event of a widget with the above R snippet. It means that R widgets
can be used as global data science scripts:
var nCcor = this.getEnvironmentValues().getNumber("gmCorrelation");
var sCor = nCcor.toString();
console.log("Margin Correlation: " + sCor);
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 49
Once you have added a widget to the canvas, you can then use its Builder Panel, Styling Panel,
and Action Menu to configure its styling and runtime behavior, and even write script to configure
how it interacts with other widgets.
If you need more information about any script API in analytics designer, you can read through the
API Reference document which you can open from the help portal:
https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/latest/en-US/index.html
This is very useful, for example, if you need a specific user interface element, a particular
visualization of data, or a certain functionality in your analytic application that is not provided by
the predefined set of widgets.
Custom widgets seamlessly integrate into SAP Analytics Cloud, analytics designer.
https://help.sap.com/viewer/0ac8c6754ff84605a4372468d002f2bf/latest/en-US.
The action menu is a dynamic menu and is only visible if the widget is selected. Different
widgets have different options available, and some of the options are not available in view mode.
5.6 Table
and other details. However, both are important means to present data and to enable end users
to directly interact with data.
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[]
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[]
Widget Concepts, APIs, and Usages 54
Returns the selections of the chart. You can use the elements of the returned array with the
function DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html).
getSelections(): Selection[]
Returns the selections of the chart. You can use the elements of the returned array with the
function DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html).
removeDimension
removeDimension(dimension: string|Dimension): void
Removes the dimension from whichever axis it is present on. If the dimension is neither on the
Rows nor Columns axis, the operation is ignored.
Example:
Table_1.removeDimension("Location_4nm2e04531");
onResultChanged
onResultChanged()
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", Feed.CategoryAxis);
Widget Concepts, APIs, and Usages 55
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.
Example:
Chart_1.addMeasure("[Account_BestRunJ_sold].[parentId].&[Gross_MarginPlan]",Feed.Va
lueAxis);
getDataSource
getDataSource(): DataSource
Returns the data source of the chart. If the chart has no data source, undefined is returned.
getForecast
getForecast(): Forecast
Returns the forecast of the chart.
getMeasure
getMeasures(feed: Feed): Measure[]
Returns the measures of the feed.
Example:
var measures = Chart_1.getMeasures(Feed.ValueAxis);
getSelections
getSelections(): Selection[]
Returns the selections of the chart. You can use elements of the returned array with the function
DataSource.getData() to get the value of a cell. See also the documentation of Selection
(https://help.sap.com/doc/958d4c11261f42e992e8d01a4c0dde25/2019.8/en-
US/doc/Selection.html ).
getSmartGrouping
getSmartGrouping(): SmartGrouping
removeDimension
removeDimension(dimension: string|Dimension, feed: Feed): void
Removes the dimension from the feed.
Example:
Chart_1.removeDimension("Location_4nm2e04531", Feed.CategoryAxis);
Widget Concepts, APIs, and Usages 56
removeMeasure
removeMeasure(measure: string|Measure, feed: Feed): void
Example:
Chart_1.removeMeasure("[Account_BestRunJ_sold].[parentId].&[Gross_MarginPlan]",Feed
.ValueAxis);
onResultChanged
onResultChanged()
onSelect
onSelect()
Called when the user selects within the chart.
There are several use cases when trying to retrieve result set, such as with or without input
selection. And as an application designer, you can also define the offset of dataset and the
number of limits that you want to get.
// No input parameter, all data points of Chart_1 will be in result
// set
// Both dimension and measure context are returned, including parent
// information if it has hierarchy structure
Chart_1.getDataSource().getResultset();
// Specify offset and limit. Two data cells from the beginning are
// returned.
Table_1.getDataSource().getResultset(null, 0, 2);
The dimension member information you are interested in can be retrieved according to selection
as well. The information includes ID, description, and parent ID.
// Get the dimension member of "California"
Widget Concepts, APIs, and Usages 57
For table widget, the application designer can get the number of visible columns or rows in a table
via APIs.
Table_1.getRowCount();
Table_1.getColumnCount();
Example:
In the following example, the Prompt dialog of a table’s data source is opened:
Table_1.getDataSource().openPromptDialog();
Example:
In the following example, the names of all variables of a data source are printed to the browser
console:
var aVariables = Table_1.getDataSource().getVariables();
for (var i = 0; i < aVariables.length; i++) {
console.log(aVariables[i].id);
}
Widget Concepts, APIs, and Usages 58
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 39). 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 40).
Figure 39: Prompt Dialog: Variable Values Are Applied to the Widget Only
Figure 40: 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"]});
5.9.3.3 Comparisons
If the variable supports comparison operations <, <=, >, and >= you can set the variable value as
follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {less: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {lessOrEqual: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {greater: "5"});
Table_1.getDataSource().setVariableValue("VAR_NAME", {greaterOrEqual: "5"});
5.9.3.4 Ranges
If the variable supports a range of variable values, you can set the variable value as follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {from: "5", to: "7"});
If the variable supports excluding a range of variable values, you can set the variable value as
follows:
Example:
Table_1.getDataSource().setVariableValue("VAR_NAME", {exclude: true, from: "5", to:
"7"});
Note: If you remove a variable value from a mandatory variable, then this operation is ignored.
Widget Concepts, APIs, and Usages 60
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 61
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
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 62
Need to add at least two widgets to a popup to run the popup as designed
We recommend you add at least two widgets to a popup as widgets are the visualization of the
popup. If no widgets are added, you won't see the popup displayed when you trigger it while
running the analytic application. If only one widget is added, the height and width you set for the
popup won't take effect.
When a table or chart in the canvas act as the source widget of a filter line widget in a
popup, source widget can’t find the filter line as its reference after reloading the analytic
application
In the case when a table or chart in the canvas act as the source widget of a filter line widget in a
popup and you reopen or refresh the analytic application, you will find the filter line isn’t listed in
the reference list of the table or chart widget after you choose Find Reference. This is because
currently we don't initiate the filter line widget in the popup when you first entering an analytic
application.
To solve this, for now we recommend you activate the popups by clicking on each of them. Then
the reference list will display all relevant results.
The text style can be configured by each segment. In-place edit the text by double-clicking the
Text input field of Text_Title in Canvas and config the style of description.
The script variable can be exposed as URL parameter if you switch on the option. For example,
if you input p_ScriptVariable_Currency=CNY in the URL link, you’ll get the following:
Configure Feeds
The RSS feeds in the widget can be updated dynamically at runtime via APIs when you select in
Chart_RSSCategory in Present relevant RSS articles.
Example:
If you select Business in the chart, BBC Business is added in the list of feeds and selected by
default after running the scripts below:
RssReader_Content.removeAllFeeds();
RssReader_Content.addFeed("BBCBusiness","http://feeds.bbci.co.uk/news/business/rss.
xml");
RssReader_Content.setSelectedFeed("http://feeds.bbci.co.uk/news/business/rss.xml")
5.13 R Visualization
Use the R Visualization widget to leverage R scripts. It allows you to build your own visualizations,
do calculation, and more. Refer to sample Show R Visualization result in Text for the most
frequently used APIs.
In the script of R Visualization, you can define parameters to get input values or return results
calculated in the script.
Example:
Configure the title of visualization R Visualization in Show R Visualization result in Text per
location by input parameter:
RVisualization.getInputParameters().setString("titleParam", "Gross Margin of
Oregon");
Example:
Calculate the total of gross margin in RVisualization script, and return the result:
RVisualization.getEnvironmentValues().getNumber("totalSum");
Configure the data source of the R Visualization via APIs. For example, in Show R Visualization
result in Text, the dimension filter is set to Oregon when you change location via
Dropdown_Location by this
RVisualization.getDataFrame("BestRunJuice_SampleModel").getDataSource().setDimensio
nFilter("Location_4nm2e04531", ["CT13", "CT14", "CT15", "CT16", "CT17", "CT18"]);
Widget Concepts, APIs, and Usages 64
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();
Layout.getTop(): Unit; // Returns the top margin between the widget that you define
layout for and the widget's parent container.
Layout.setTop(value: Unit); // Sets the top margin between the widget that you
define layout for and the widget's parent container.
Layout.getBottom(): Unit; // Returns the bottom margin between the widget that you
define layout for and the widget's parent container.
Layout.setBottom(value: Unit); // Sets the bottom margin between the widget that
you define layout for and the widget's parent container.
Layout.getWidth(): Unit; // Returns the width of the widget that you define layout
for.
Layout.setWidth(value: Unit); // Sets the width of the widget that you define
layout for.
Layout.getHeight(): Unit; // Returns the height of the widget that you define
layout for.
Layout.setHeight(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 66
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(LayoutValue.create(98,
LayoutUnit.Percent));
Panel_2.getLayout().setBottom(LayoutValue.Auto);
Panel_2.getLayout().setHeight(LayoutValue.create(376,
LayoutUnit.Pixel));
Panel_3.getLayout().setBottom(LayoutValue.Auto);
Panel_3.getLayout().setLeft(LayoutValue.create(1,
LayoutUnit.Percent));
Widget Concepts, APIs, and Usages 67
Panel_3.getLayout().setTop(LayoutValue.create(476,
LayoutUnit.Pixel));
if (screenWidth < 500) {
//one column
Panel_3.getLayout().setHeight(LayoutValue.create(
(baseChartHeight + padding) * 4 + padding * 3 +
Table_1.getLayout().getHeight().value, LayoutUnit.Pixel));
} else {
//two columns
Panel_3.getLayout().setHeight(LayoutValue.create(840,
LayoutUnit.Pixel));
}
Panel_3.setVisible(true);
}
With the Layout APIs, you have all the flexibility to adjust the application based on the screen size,
to create a responsive application in an analytic application.
Typical Patterns and Best Practices 68
To achieve this, we will add an icon that represents a Chart and another that represents a Table.
Then, we will write scripts for each of the images/icon we added to make it so that when we click
on the Chart icon, the chart will appear, and the Table will be invisible, and vice versa.
Our default setting, shown when the application is first run, will be to make the Table visible (and
the Chart invisible).
The result will look like this when we first run the application:
And if we click on the image, we will get the Chart and the image will change its look to a
Table icon and if we select it we come back to the view of the previous screenshot:
Prerequisites for this use case is having already added a Table and a Chart to your canvas.
Please select, for example, the model BestRun_Advanced as data source.
icon to
Switch_to_Table_display and the
Chart.setVisible(true);
Table.setVisible(false);
Switch_to_Table_display.setVisible(true);
Switch_to_Chart_display.setVisible(false);
on the button.
Chart.setVisible(false);
Table.setVisible(true);
Switch_to_Table_display.setVisible(false);
Switch_to_Chart_display.setVisible(true);
Typical Patterns and Best Practices 72
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 73
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 76
Table.getDataSource().setDimensionFilter("Account_BestRunJ_so
ld",selectedId);
Chart.addMeasure(selectedId, Feed.ValueAxis);
if (measures.length > 0) {
for (var i = 0; i < measures.length; i++){
// Measure
Dropdown_Measures.addItem(measures[i].id,
measures[i].description);
if (selectedKey === "" && i === 0) {
selectedKey = measures[i].id;
Dropdown_Measures.setSelectedKey(selectedKey);
console.log(["selectedKey ", selectedKey]);
}
console.log(["CurrentMeasure ", measures]);
}
}
Utils.setMeasureFilter(selectedKey);
Typical Patterns and Best Practices 79
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 80
Prerequisites for this use case is having already added a table and a chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
Chart.removeMeasure(CurrentMeasureFilterSelection[i]
, Feed.ValueAxis);
}
}
// add Measures
Table.getDataSource().setDimensionFilter("Account_Be
stRunJ_sold",selectedIds);
for (i = 0; i < selectedIds.length; i++) {
Chart.addMeasure(selectedIds[i], Feed.ValueAxis);
}
// save the current selection into global variable
CurrentMeasureFilterSelection = selectedIds;
similarly select .
Utils.setMeasureFilter(CheckboxGroup_Measures.getSel
ectedKeys());
Typical Patterns and Best Practices 87
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
Utils.setMeasureFilter(AllMeasures);
if (measures.length > 0) {
for (var i = 0; i < measures.length; i++) {
// add the Measure to checkbox group
CheckboxGroup_Measures.addItem(measures[i].id,measur
es[i].description);
//add the measure to the selecedKeys
selectedKeys.push(measures[i].id);
CheckboxGroup_Measures.setSelectedKeys(selectedKeys)
;
console.log(["CurrentMeasure ", measures]);
}
}
Now let’s see how it looks like. Application when it’s first run:
Click on Run Analytic Application in the
upper right side of the page and the result
should look something like this:
Let us only select a few measures and see Table after clicking on “Remove all”:
how the Table will change.
In the screenshot on the right, 4 measures
are chosen (Gross Margin Plan, Quantity
Sold, Original Sales Price abs Dev, and
Discount).
After selecting the measures, please click
on “set selected” to update the Table/Chart
with your chosen measures.
Instead of loading all the dimensions in our data set into a Checkbox group or a Dropdown widget,
in this use case, we will select specific dimensions to load into a Filter Line.
Typical Patterns and Best Practices 90
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 91
Prerequisites for this use case is having already added a Table and a Chart to your canvas. To
have all the functionalities in this use case, please first go through the Switching between Table
and Chart exercise.
the and
respectively (please refer to the
“Switching between Table and
Chart” Exercise).
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Location_4nm2e04531");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Product_3e315003an");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Sales_Manager__5w3m5d06b5");
Chart.getDataSource().copyDimensionFilterFrom(Table.getDataSou
rce(), "Store_3z2g5g06m4.Store_GEOID");
Typical Patterns and Best Practices 94
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 96
Location_4nm2e04531 Location
Product_3e315003an Product
Store_3z2g5g06m4 Store
// Table
Table.removeDimension(CurrentDimension);
Table.addDimensionToRows(sel);
//Chart
Chart.removeDimension(CurrentDimension, Feed.CategoryAxis);
Chart.addDimension(sel, Feed.CategoryAxis);
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id, 'Flat
Presentation');
}
else {
Typical Patterns and Best Practices 100
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ', CurrentDimension]);
// Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
// Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id, 'Flat
Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ', CurrentDimension]);
//Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 102
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 103
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 104
CheckboxGroup_Columns.removeAllItems();
CheckboxGroup_Rows.removeAllItems();
CheckboxGroup_Free.removeAllItems();
CurrentDimensionColumn = ArrayUtils.create(Type.string);
CurrentDimensionRows = ArrayUtils.create(Type.string);
console.log(["CurrentDimensionColumn should empty",
CurrentDimensionColumn.slice()]);
console.log(["CurrentDimensionRows should empty",
CurrentDimensionRows.slice()]);
// Dimension in Columns
var dimCol = Table.getDimensionsOnColumns();
if (dimCol.length > 0) {
for (var i = 0; i < dimCol.length; i++) {
CurrentDimensionColumn.push(dimCol[i].id);
console.log(["CurrentDimensionColumn ",
dimCol[i].id]);
}
}
Typical Patterns and Best Practices 117
// Dimension in Rows
var dimRows = Table.getDimensionsOnRows();
if (dimRows.length > 0) {
for (i = 0; i < dimRows.length; i++) {
CurrentDimensionRows.push(dimRows[i].id);
console.log(["CurrentDimensionRows ",
dimRows[i].id]);
}
}
CheckboxGroup_AllDimensions.setSelectedKeys([AllDimension
s[i]]);
var dimdesc =
CheckboxGroup_AllDimensions.getSelectedTexts();
CheckboxGroup_Free.addItem(AllDimensions[i],
dimdesc[0]);
console.log(["AllDimensions",AllDimensions[i],
dimdesc[0]]);
}
}
}
console.log(["CurrentDimensionColumn",
CurrentDimensionColumn]);
console.log(["CurrentDimensionRows",
CurrentDimensionRows]);
CheckboxGroup_Free.setSelectedKeys([CurrentDimensionRows[
i]]);
dimdesc = CheckboxGroup_Free.getSelectedTexts();
CheckboxGroup_Rows.addItem(CurrentDimensionRows[i],
dimdesc[0]);
CheckboxGroup_Free.removeItem(CurrentDimensionRows[i]);
}
}
}
if (CurrentDimensionColumn.length > 0) {
for (i = 0; i < CurrentDimensionColumn.length; i++) {
if (CurrentDimensionColumn[i] !== "") {
CheckboxGroup_Free.setSelectedKeys([CurrentDimensionColum
n[i]]);
dimdesc = CheckboxGroup_Free.getSelectedTexts();
CheckboxGroup_Columns.addItem(CurrentDimensionColumn[i],
dimdesc[0]);
CheckboxGroup_Free.removeItem(CurrentDimensionColumn[i]);
}
}
}
Typical Patterns and Best Practices 118
Utils.setMeasureFilter(CheckboxGroup_Measures.getSelected
Keys());
CheckboxGroup_Measures.setSelectedKeys(AllMeasures);
Utils.setMeasureFilter(AllMeasures);
Utils.setDimensionCheckboxes();
Utils.setDimensionCheckboxes();
Typical Patterns and Best Practices 120
Utils.setDimensionCheckboxes();
Utils.setMeasureFilter(selectedKeys);
Utils.setDimensionCheckboxes();
Typical Patterns and Best Practices 122
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 124
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 125
There, enter
“Dropdown_MeasureGroup” as the
Name.
Typical Patterns and Best Practices 126
Actual Actual
Plan Plan
_Abs Absolute
_Percent % Deviation
Popup_Settings.open();
Table.getDataSource().setDimensionFilter("Account_Bes
tRunJ_sold", selectedId);
Chart.addMeasure(selectedId, Feed.ValueAxis);
Typical Patterns and Best Practices 136
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_MarginPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Gross_Margin_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup === 'Discount') {
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[DiscountActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[DiscountPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Discount_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Discount_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup === 'Quantity_Sold') {
Typical Patterns and Best Practices 137
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_soldPlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Quantity_sold_Percent]", Feed.ValueAxis);
}
else if (CurrentMeasureGroup ===
'Original_Sales_Price') {
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PriceActual]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_PricePlan]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Abs]", Feed.ValueAxis);
Chart.removeMeasure("[Account_BestRunJ_sold].[parentI
d].&[Original_Sales_Price_Percent]", Feed.ValueAxis);
}
Chart.removeMeasure(CurrentMeasureFilterSelectionPopu
p[i], Feed.ValueAxis);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = ArrayUtils.create(Type.string);
CurrentMeasureSelection = Selected_Measures;
Chart.removeMeasure(CurrentMeasureFilterSelectionPopu
p[i], Feed.ValueAxis);
}
// help variables
var Filter_Pattern_1 =
"[Account_BestRunJ_sold].[parentId].&[";
var Filter_Pattern_2 = "]";
var Filter_Area = ArrayUtils.create(Type.string);
Table.getDataSource().removeDimensionFilter("Account_
BestRunJ_sold");
Table.getDataSource().setDimensionFilter("Account_Bes
tRunJ_sold", Filter_Area);
In a Table, a user will be able to select a measure cell, a dimension cell, or a data cell. Each will
open a popup window that displays information about the selected element in a trend chart.
In the Chart, a user will be able to select a dimension cell and a measure/dimension chart bar (for
example, Gross Margin Plan for Lemonade).
There are also two Dropdown lists, one for dimensions and the other for hierarchies. The list of
dimensions let the user choose which dimension filter they want to use on the Table/Chart. In this
use case, we have chosen 4 dimensions; Location, Product, Store, and Sales Manager.
The second Dropdown list displays the available hierarchies that can be used to change how the
data is displayed.
Note: In this example, only single selection is supported for the Table and Chart.
The result will look like this when we run the application:
And when a cell is chosen, a popup window like the one in the screenshot will appear (In this
screenshot, the dimension cell of Los Angeles was clicked on in the Table):
Typical Patterns and Best Practices 143
Prerequisites for this use case is having already added a functioning Table and a Chart to your
canvas. To have all the functionalities in this use case, please first go through the Switching
between Table and Chart exercise.
It is recommended to use the same names as that exercise for the Table and Chart so that the
scripts in this use case don’t have to be altered.
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
'Flat Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ',
CurrentDimension]);
Details_Chart.removeMeasure(CurrentMeasures[i],
Feed.ValueAxis);
Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
}
//Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
CurrentDetailsMeasures.push(memberId);
Typical Patterns and Best Practices 155
Popup_show = true;
}
// Dimension
else {
console.log(['Selection Dimension: ',
dimensionId]);
console.log(['Selection Member: ', memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
if (Popup_show === true) {
Popup_Details.open();
}
if (sel.length > 0) {
Details_Chart.getDataSource().removeDimensionFilter(C
urrentDimension);
Details_Chart.addMeasure(memberId,
Feed.ValueAxis);
CurrentDetailsMeasures.push(memberId);
Popup_show = true;
}
Typical Patterns and Best Practices 157
// Dimension
else {
console.log(['Selection Dimension: ',
dimensionId]);
console.log(['Selection Member: ',
memberId]);
Details_Chart.getDataSource().setDimensionFilter(dime
nsionId, memberId);
Popup_show = true;
}
}
}
}
Details_Chart.removeMeasure(CurrentDetailsMeasures[i]
, Feed.ValueAxis);
}
CurrentDetailsMeasures =
ArrayUtils.create(Type.string);
// loop
for (var i = 0; i < hierarchies.length; i++) {
if (hierarchies[i].id === '__FLAT__') {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
'Flat Presentation');
}
else {
Dropdown_Hierarchies.addItem(hierarchies[i].id,
hierarchies[i].description);
if (flag === true) {
var hierarchy = hierarchies[i].id;
flag = false;
}
}
}
// write hierarchy information to browser console
console.log(['Hierarchy: ', hierarchy]);
console.log(['Current Dimension: ',
CurrentDimension]);
//Table
Table.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
//Chart
Chart.getDataSource().setHierarchy(CurrentDimension,
'__FLAT__');
Typical Patterns and Best Practices 160
//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 166
REGION01 LATAM
REGION02 EMEA
REGION03 NA
REGION04 APJ
There, enter
“RadioButtonGroup_Country” as the
Name, choose Vertical Layout as the
Display Option, and toggle the Label
Text button to enable it and write
“Country” as the Label Text.
ALL All
# load package
library(wordcloud)
# get words
words <- BestRunBike_Customer_Complaint$`Complaint
Category`
# get frequency
frequency <- BestRunBike_Customer_Complaint$Count
if (exists("colorValue")) {
myColor <- colorValue
} else {
myColor <- "Oranges"
}
# generate word cloud
wordcloud(words, frequency, scale = c(4, 1),
rot.per=0.2, colors=brewer.pal(8, myColor))
# get words
words <- BestRunBike_Customer_Complaint$`Complaint
Category`
# get frequency
frequency <- BestRunBike_Customer_Complaint$Count
if (exists("colValue")) {
myColor <- colValue
} else {
myColor <- "Oranges"
}
# generate word cloud
wordcloud(words, frequency, scale = c(4, 1),
rot.per=0.2, colors=brewer.pal(8, myColor))
if (sel.length > 0) {
var selection = sel[0];
console.log(['Selection [0] : ', selection]);
Chart_Complaints.getDataSource().setDimensionFilter(dim
ensionId, memberId);
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r(dimensionId, memberId);
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r(dimensionId, memberId);
Hidden_DropDown_Customer.setSelectedKey(memberId);
var text =
Hidden_DropDown_Customer.getSelectedText();
Title_Complaints.applyText("Complaints for Customer
" + text);
}
}
RadioButtonGroup_Country.removeAllItems();
RadioButtonGroup_Country.addItem("ALL", "All");
RadioButtonGroup_Country.setSelectedKey("ALL");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY011]", "Mexico");
} else if (sel === "REGION02") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY021]", "Dubai");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY022]", "Germany");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY023]", "Great Britian");
} else if (sel === "REGION03") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY031]", "USA East");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY032]", "USA West");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY033]", "Canada");
} else if (sel === "REGION04") {
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY041]", "India");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY042]", "China");
RadioButtonGroup_Country.addItem("[Country].[Region].&[
COUNTRY043]", "Australia");
}
Table_Customer.getDataSource().setDimensionFilter("Regi
on",sel);
Chart_Complaints.getDataSource().setDimensionFilter("Re
gion",sel);
RVisualization_WordCloud_2018.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Region",sel);
RVisualization_WordCloud_2019.getDataFrame("BestRunBike
_Customer_Complaint").getDataSource().setDimensionFilte
r("Region",sel);
Table_Customer.getDataSource().removeDimensionFilter("C
ountry");
Typical Patterns and Best Practices 182
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 183
RVisualization_WordCloud_2018.getInputParameters().setS
tring("colorValue", sel);
RVisualization_WordCloud_2019.getInputParameters().setS
tring("colValue", sel);
var list =
Table_Customer.getDataSource().getMembers("Customer_",
1000);
if (list.length !== 0) {
for (var i = 0; i < list.length; i++) {
console.log(['List Dimension: ', i ,
list[i].displayId]);
console.log(['List Description: ', i ,
list[i].description]);
console.log(['List Member: ', i , list[i].id]);
Hidden_DropDown_Customer.addItem(list[i].id,
list[i].description);
}
}
Typical Patterns and Best Practices 184
If the passed value is prefixed with an asterisk (*), then the value is applied as a factor to the
present cell value. For example, applying the following script after the script above
Table_1.getPlanning().setUserInput({"sap.epm:Account":
"[sap.epm:Account].[parentId].&[TAXES]", "sap.epm:ProfitAndLoss_Version02":
"public.Actual"}, "*0.5");
Table_1.getPlanning().submitData();
results in a cell value (raw value) of 61728394.5, which is displayed as 61.73 (formatted value).
Another example shows a combination of a table with an input field. The value of the input field is
applied as the new cell value to the first selected cell of the table:
var selectedCell = Table_1.getSelections()[0];
Typical Patterns and Best Practices 185
7 Planning
And what can you not expect? In analytics designer you cannot use Input Tasks and Planning
scripting is not possible for models based on BPC Write-Back.
These icons are greyed out if no table cell with a planning model is selected.
To get the Planning Table object, use the script below. If the table has no planning model
assigned, it will return undefined.
Table.getPlanning(): Planning | undefined
Scripting will perform the same planning actions that could be done via UI. The benefits of
scripting are augmented in cases which you want to minimize the number of clicks from your user,
personalize your UI or when a special customer requirement can’t be fulfilled with standard
planning behavior.
Data can’t be changed during design time, and you can enable the usage of planning features
during runtime in two different ways:
• In the table designer UI: You can find in the Builder panel, section Properties, a box
called Planning enabled.
Planning 187
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 192
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
This check is necessary because a user can’t perform certain operations on a table, like
setState() and getState(), if the model is not data locking enabled.
In the following example, the data locking object is retrieved and printed to the console. A data
locking object is returned if data locking is enabled on the model.
var planning = Table_1.getPlanning();
console.log(planning.getDataLocking());
Note that you can also check if a model is data locking enabled in SAP Analytic Cloud by checking
the model preferences (see Figure 67).
In following example, the data locking state for a selected cell of a table is retrieved:
var selection = Table_1.getSelections()[0];
Planning 194
var selectionLockState =
Table_1.getPlanning().getDataLocking().getState(selection);
In order to create a selection on the table, you can either select the cell in the table manually or
you can create the selection string yourself in the script editor.
If the state of the selection can't be determined, then the method returns undefined. This occurs
if one of the following situations applies:
• The selection is invalid.
• The cell referenced by the selection is not found.
• The cell is in an unknown state.
• The cell has been created using "Add Calculation" at runtime.
If you have activated the Show Locks option for the table, then the “lock” icons will be updated
after the method has finished running.
The method returns true if the set operation was successful and false otherwise.
You can't set the data locking state on a private version. In this case, the following message is
displayed:
“You can only set data locks on public versions. Please use a public version and try again.”
If you attempt to set the data locking state DataLockingState.Mixed, then the following message
is displayed:
“You can't set the state with the value 'mixed'. Please specify either 'open', 'restricted' or 'locked'
as value.”
The same message is displayed at runtime if you attempt to execute the script and the script fails.
If you select multiple cells and attempt to set the data locking state, the data locking state will be
applied to the first selection only.
In the following example, the data locking state is set for a selected table cell:
var selection = Table_1.getSelections()[0];
Planning 195
var isSetStateSuccessful =
Table_1.getPlanning().getDataLocking().setState(selection,
DataLockingState.Locked);
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.
Predictive 196
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 197
Figure 70: Time Series Chart: Select the Interested Data Point
Predictive 198
Basically, Smart Grouping can be switched on and off via two ways: the setting in Builder Panel
at design time,
Sample Gain insights into the data demonstrates how to trigger Smart Discovery via APIs.
var ds = Chart_Forecast.getDataSource();
var members = ds.getMembers("Product_3e315003an");
var SDsetting = SmartDiscoveryDimensionSettings.create(ds, "Product_3e315003an",
[members[1]]);
SDsetting.setIncludedDimensions(["Location_4nm2e04531", "Store_3z2g5g06m4"]);
Predictive 200
SDsetting.setIncludedMeasures(["[Account_BestRunJ_sold].[parentId].&[Gross_Margin]"
, "[Account_BestRunJ_sold].[parentId].&[Discount]"]);
SmartDiscovery.buildStory(SDsetting);
In this example, Smart Discovery is invoked via clicking “More Insights…” to discover Product
with Dark Beer as the target group. In addition, two more measures (Gross Margin and Discount)
and two more dimensions (Location and Store) are included in the analysis.
Write Analytic Design scripts to launch Search To Insight. At runtime, the analytic application user
can open the Search To Insight dialog to get deep and flexible insights of their data.
var mode = SearchToInsightDialogMode.Simple;
SearchToInsight_1.openDialog("Gross Margin by Location", mode, true, true);
9 OData
Versions 1.0, 2.0, and 3.0 are released under the Microsoft Open Specification Promise.
Version 4.0 was standardized at OASIS, with a release in March 2014. In April 2015 OASIS
submitted OData v4 and OData JSON Format v4 to ISO/IEC JTC 1 for approval as an
international standard.
“The protocol enables the creation and consumption of REST APIs, which allow Web clients to
publish and edit resources, identified using URLs and defined in a data model, using simple HTTP
messages. OData shares some similarities with JDBC and with ODBC; like ODBC, OData is not
limited to relational databases.”
Source: https://en.wikipedia.org/wiki/Open_Data_Protocol
For OData, CORS should be configured on backend analogous to 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 (available with wave 2020.4)
o SAP HANA (available with wave 2020.4)
o SAP Business and Consolidation (BPC) (available with wave 2020.4)
• 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 204
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 205
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 206
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 209
var totalnumberofseats =
ConvertUtils.integerToString(ret.value[0].Totalnumberofseats);
var currency = ret.value[0].Currency;
info = "Your flight price was " + flightprice + " " + currency +
". " + "There are " + numberofoccupiedseats +
" occupied from " + totalnumberofseats + " seats in total.";
}
Text_5.applyText("" + info);
Run the application and book a flight and cancel a flight to see the error messages.
To create a meaningful application in the sense of an intelligent application, the best would be to
display the backend data via a live connection to a BEx Query. Like this you would be able to see
the changes (the booked and canceled seats) in the data directly after clicking the buttons and
executing the actions.
Therefore, in Analytics Designer you have programmatic access to these data, which can be used
for any purposes other than visualization in table or 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:
• Retrieving a single OData Entity from an EntitySet, by specifying the key to the entity.
(analogous to selecting a single row from a SQL table via SELECT * FROM T1 WHERE ID =
<id>).
ODataResult<T>: {
ok: boolean;
value: T; //depends on payload of action or entity type
error: ODataError;
}
ODataError: {
code: string;
message: string;
target: string;
details: ODataError[];
}
Post Message API 212
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 213
10.1.2 onPostMessageReceived
This is to handle messages sent from the host parent or top HTML page in the analytic application.
In scenario 2 depicted below, the event can also handle messages sent from an HTML page
embedded via the web page widget in an analytic application.
Note: We advise you always to check the origin when receiving an event-triggered message,
because a malicious site can change the location of the window and therefore intercept the data
you sent using the postMessage event without your knowledge.
In the current scenario, the parent window which hosts the iFrame can post messages to the
analytic application's iFrame window of specific target origin. The messages posted are then
retrieved by the analytic application and trigger changes accordingly, such as updating some input
data.
10.1.3 Example
You can embed an analytic application in a host HTML page. The URL of the host HTML page is
http://localhost:8080.
First, you want to allow end users to post the company selection in the analytic application to the
host HTML page. Write the script below for the sending button:
var message = RadioButtonGroup_Company.getSelectedText();
Application.postMessage(PostMessageReceiver.Parent, message,
"http://localhost:8080");
Then you want to allow end users to display the message received from the Host HTML page in
a text box of the embedded analytic application.
if (origin == "http://localhost:8080") {
Text_ReceivedMessage.applyText(message);
}
The event for handling messages sent from embedded application is: Once the messages is
received, the host application can use the event onPostMessageReceived() to handle the
messages.
The End and the Future 216
12 Important Links
Please open the SAP Help page to find many more information about SAP Analytics Cloud,
analytics designer:
https://help.sap.com/viewer/product/SAP_ANALYTICS_CLOUD/release/en-US
No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permissio n 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 distr ibutors 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 S AP 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 thei r respective companies. See
www.sap.com/copyright for additional trademark information and notices.