Using Common JavaScript Options in a Script to Enhance a Story

Objective

After completing this lesson, you will be able to enhance a story using common JavaScript options.

Local Script Variables

In scripts, you can "store" a value in a variable. There are two types of variables: local and global variables. We'll cover the global ones later in the course. Local script variables can be created using the var command. They're valid only within the script where they're assigned. When the script is fully processed, the variable loses its value.

Local Script Variables

var <NameOfVariable> = <ValueOfVariable>;

Code showing examples of script variables.

Keep in mind:

  • You must assign a value in the var statement
  • The assigned value defines the data type of the variable

Whatever type of variable you create, you've to give it a name as an identifier, like counter, selectedCountry, myList. Developers typically use specific naming conventions to make it easy for everyone to read the code. If you’re interested in learning more about this topic, refer to the following document and align to a consistent definition with your story developer colleagues: Devopedia - Naming Conventions

Single, Double, and Triple Equals (===) Operators

Single equals (=) are assignment operators. You use them to assign a value to a variable.

Example of script in the script editor that uses single equals to assign a value to a variable.

Triple equals (===) are comparison operators. If you use triple equal, then both the values and the types are compared.

Example of script in the script editor that uses triple equals in line two.

Double equals (==) are comparison operators. With double equal, the values are compared but the types are not. SAP Analytics Cloud does not support automatic type conversion so do not use double equals in any script.

Example of scripting that includes double equals and the error that is produced in the script editor. Do not use double equals.

Writing to the Console

A very common technique to keep track of variable values or script processing is to make use of the browser console. You can write text or variable values into the console using the console.log(); command.

To access the console from the browser you need to open the Developer Tools from the browser toolbar and switch to the Console tab.

Conditional Execution Statements and Loops

If Then Else Statements

Code Snippet
123456
if (condition) { // this block will be executed if condition is true } else { // this block will be executed if condition is false }
Typical comparison patterns:Logical operators:
===(equal)&&(and)
!==(not equal)||(or)
<(less than)!(not)
<=(less than or equal to)  
>(greater than)  
>=(greater than or equal to)  

Switch Statements

Code Snippet
12345678910111213
var selectedCountry = Dropdown1.getSelectedText(); switch (selectedCountry) { case "Germany": // code that is relevant for Germany break; case "USA": // code that is relevant for USA break; default: // code that is relevant for all other countries }

You can use the switch statement to select one out of multiple code sections. The expression (in our case selectedCountry) is compared with the values of each case. If it matches, the associated code section executes. To stop further processing of the switch statement, you use the break statement to jump out of the switch.

If you do not use a break all following lines will be processed! This includes all following case statements regardless of its value.

Loops: For

for (statement1; statement 2; statement 3) { New line: // code lines to be executed. New line: }

In the example above, you can see three statements. They correspond to the following:

  • Statement 1: Declares the variable for the loop iterator
  • Statement 2: Is the condition that is checked before code lines are executed
  • Statement 3: Is the change to the loop iterator that is executed each time the enclosed code lines were executed

For example, you want to log all hierarchies from data source to console with for so you write the following script:

Code Snippet
123456
var Hierarchies = TBL_Quantity.getDataSource().getHierarchies("0D_NW_PRID"); for (var j=0; j<Hierarchies.length; j++){ console.log(Hierarchies[j].id +" - " + Hierarchies[j].description); }

The statements used in the script are highlighted below.

The code from above with the statements highlighted. Statement1 is var j=0. Statement 2 is j<Hierarchies.length. Statement 3 is j++.)
  • Statement 1: var j=0
  • Statement 2: j<Hierarchies.length
  • Statement 3: j++

For loops are widely used, for example, they're used to loop over the entries of an array which you will see in an exercise later in the course.

Loops: While

While loops are similar to for loops but with fewer statements.

Code Snippet
1234
while (condition) { // this block will be executed if condition is true }

For example, you want to log all hierarchies from data source to console with while, so you write the following script:

Code Snippet
12345678
var Hierarchies = TBL_Quantity.getDataSource().getHierarchies("0D_NW_PRID"); var x = 0; while (x < Hierarchies.length) { console.log(Hierarchies[x].id +" - " + Hierarchies[x].description); x++; }

Don’t forget to change the variable used in condition!

Enhance a Story with Conditional Execution

Business Scenario: Your team makes a request to change how the story is displayed when it is opened. They want to only see the KPI tile on start up and then, when they click one of the tiles, the tab strip displays along with the tab that corresponds to the selected tile.

This short video will walk you through the final story and scripting required.

Simulate the Steps

The practice exercise below simulates being in Advanced Mode in SAP Analytics Cloud and takes you through adding the scripting required to create the final story shown in the demo video.

Task Flow: In this practice exercise, you will:

  • Ensure the tab strip is set to hidden on start up
  • Define the code for the Tax and Order Quantity charts
  • Test the scripting in the story

Arrays in a Script

Working with arrays is essential in many situations. Some command APIs return an array and you should know how to handle them.

In this lesson, we introduce the concept of arrays as they can be returned in APIs so it's important that you understand what they are. However, in the next lesson you will apply your knowledge when you complete an exercise containing arrays, as well as concepts such as global script variables and script functions.

An array is something like a list of items. When you work with them in script, you typically:

  • Access a single element by its position (also called "index") on the list
  • Loop over the whole list and process each element one after the other
Example of an array in a getResultsSet event in a script.

Arrays are identified by [ ] as shown in the previous example above and can be:

  1. Printed to console
    Code Snippet
    123
    var resultset = Table_1.getDataSource().getResultSet(); console.log(resultset);
  2. Accessed with loop
    Code Snippet
    12345
    var resultset = Table_1.getDataSource().getResultSet(); for (var x=0; x<resultset.length; x++){ console.log(resultset[x]["@MeasureDimension"].rawValue); }
  3. Accessed with index
    Code Snippet
    123
    var resultset = Table_1.getDataSource().getResultSet(); console.log(resultset[1]);

Note

Like many programming languages, the first element in an array has the index 0.

In some scripting situations, it can be helpful to create a variable that can store more than one entry. For example, you want to store a list of widgets that should be processed or a list of measures that should be used from the script.

Scripting SituationVariable
Create empty arrayvar myList = ArrayUtils.create(Type.string);
Create filled arrayvar myList = ["Hello", "World", "Example"]
Add elementmyList.push("Hello world");
Remove last elementmyList.pop();
Read number of entriesmyList.length;

Generate Dynamic Values in Generic Navigation Widgets

In the Enhancing Generic Navigation Widgets with Scripting video, the steps in enhancing generic navigation widgets were introduced:

  1. Define the items for the widget in the Builder panel. It can be defined in three different ways:
    1. Manually, using direct input
    2. Dynamically, using scripting
    3. Dynamically, using property binding
  2. Define the action that should be executed in the widget’s onSelect script

In that lesson, you manually defined the items for the widget using direct input. In this lesson, we will look at dynamically defining the items using scripting.

The following code is an example of scripting that can be used to dynamically populate the dropdown:

Code Snippet
12345
var countries = Table_1.getDataSource().getMembers("0D_NW_BP__0D_NW_CNTRY"); for (var x = 0; x < countries.length; x++ ) { var country = countries[x]; Dropdown_1.addItem(country.id, country.description); }

As a typical example of the usage of arrays in script, we will use the example of writing all members of a dimension to a dropdown. You have to think about the right event in which to add the code. The Page_1.onInitialization() might be a good place, however, depending on how often the members might change, it might be useful to add it to the onResultChanged event of the source widget.

Array of Widgets

The API Application.getWidgets(); can return an array of widgets described by the widget search options. As an example, you can create an array of all charts in your story with a name starting with "CH_Tile". The API can also create an array of other widgets, for example Button, Image, etc.

Code for Array of Widgets

The code used to return an array of all charts in your story with a name starting with "CH_Tile":

Code Snippet
123
var tilecharts = Application.getWidgets({type:WidgetType.Chart, searchPattern:"CH_Tile"}); console.log (tilecharts);

To understand the content and structure of an array, you can send it to the Console Log and analyze its content there.

Use a Dynamic Dropdown to Enhance a Story

Business Scenario: You have been asked to enhance an existing story with a dropdown to filter the Order Quantity table by product category.

To do this, you will add the following code to the story using the onIntitialization action:

Code Snippet
123456
var ProductABCratingList = TBL_Quantity.getDataSource().getMembers("0D_NW_PRID__0D_NW_PRCAT"); for (var i=0; i<ProductABCratingList.length; i++){ if (ProductABCratingList[i].id !== ""){ DD_Product_ABC_rating.addItem(ProductABCratingList[i].displayId, ProductABCratingList[i].description); } }

You will also add the following code to the dropdown using the onSelect action:

Code Snippet
1
TBL_Quantity.getDataSource().setDimensionFilter("0D_NW_PRID__0D_NW_PRCAT", DD_Product_ABC_rating.getSelectedKey());

This short video will walk you through the final story and scripting required.

Simulate the Steps

The practice exercise below simulates being in Advanced Mode in SAP Analytics Cloud and takes you through adding the scripting required to create the final story shown in the demo video.

Task Flow: In this practice exercise, you will:

  • Add the dropdown to the story
  • Add scripting to the onIntitialization action
  • Add scripting to the onSelect action
  • Test the scripting in the story

Log in to track your progress & complete quizzes