Modify a filter / view parameter using scripting

Contents[Hide]

1. Overview

The goal of this article is to demonstrate passing various types of values to view parameters through script.

Live samples can also be viewed by visiting our script library.

2. Understanding

2.1. What is a view parameter?

A view parameter passes parameter values selected through filter controls or interactions into the parameters of metric sets. Filter controls and interactions can be set up without script, but script can be used to set parameter values as part of custom functionality.

2.2. Types of view parameters

There are many types of parameter values available, which can be found in our JavaScript API Reference. We will be covering the following most common types in this article:

2.3. What are tokens?

Tokens are predefined values that can be accessed using the white triangle to the right of a filter control. The values presented in the token dropdown list will depend on the data type. If the data type is of a time hierarchy, the list will have various convenient choices such as: Today, Current Month, Previous Year, End of Year, etc. 

Note
Using a range token in a single date/time filter will default to the beginning of that range (e.g., Current Year will be January 1st of that year).

3. Parameters values and token values

3.1. RangeNumber

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// Set the lower and upper values
viewParameter.parameterValue.lowerBoundaryValue = 100;
viewParameter.parameterValue.upperBoundaryValue = 200;

// Set the last modified time so this parameter takes precedence over any others
viewParameter.invalidateParameterValueLastModifiedTime();

// Update all the connected adapters with the newly modified values
// Includes data visualizations and filter controls
viewParameter.refreshAllAdapters();

3.2. HierarchyLevel

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Set the depth of the hierarchy to be displayed
viewParameter.parameterValue.detailsLevelDepth = 1;

// Set the top level if you wish to display more than 1 level
// Default is -1 which will use the details level depth instead
viewParameter.parameterValue.topLevelDepth = 0;

// Set the last modified time so this parameter takes precedence over any others
viewParameter.invalidateParameterValueLastModifiedTime();

// Update all the connected adapters with the newly modified values
// Includes data visualizations and filter controls
viewParameter.refreshAllAdapters();

3.3. TimeHierarchyOffset

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Set the offset of the Period over Period to be displayed
// Negative values will set the offset 'Backward'
viewParameter.parameterValue.offset = -1;

// Level value format = "Level.Code.TimeDimensionName"
// Day=0  Week=1  Month=2  Quarter=3  Half=4  Year=5
// Example: "2.54320.DueDate"

// Only modify the level index by taking a substring 
var levelUniqueName = viewParameter.parameterValue.level;
var endOfLevel = levelUniqueName.substring(levelUniqueName.indexOf('.'));

// Set the level to the level number and concatenate endOfLevel
viewParameter.parameterValue.level = "5" + endOfLevel;
// This will result in Backwards 1 Year

// Set the last modified time so this parameter takes precedence over any others
viewParameter.invalidateParameterValueLastModifiedTime();

// Update all the connected adapters with the newly modified values
// Includes data visualizations and filter controls
viewParameter.refreshAllAdapters();

3.4. CollectionMember

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// One option is to set all the necessary properties of the new member
// An easy way to get this information is to use the developer console
// to expand the objects in of viewParameter.parameterValue.values
// after you've already chosen the desired member using a filter

// Below is an example of a member value from a flat hierarchy.
// Create a new MemberValue to push onto the values array.
var memberValue = new dundas.data.MemberValue({
    "hierarchyUniqueName": "Name",
    "levelUniqueName": "Name",
    "memberKind": "Regular",
    "uniqueName": "Cable Lock.Name"
});
// When the building a member value from a multi-level hierarchy, the uniqueName
// property of the member value will heavily depend on how the hierarchy was built

// Example: 5 level Address hierarchy = "Ontario.Toronto.D.Address"
// Example: 3 level Product hierarchy = "857.C.Products"
// 857 is the productId but what's displayed is "Men's Bib-Shorts, L"

// Another option is to use the hierarchy service to get the desired member.
// Get the cellset from a visualization's metric set binding
var cellset = table1.metricSetBindings[0].dataResult.cellset;

// Get the hierarchy from the cellset based on its unique name
var hierarchy = cellset.hierarchies.filter(function (hierarchy) {
    return hierarchy.uniqueName == "Products";
})[0];

// Get the service
// We use the service instead of using this hierarchy since the 
// cellset in the table only includes what's needed to render
// so it could be an incomplete set of data
var hierarchyService = this.getService("HierarchyService");

// getMembers will return all the members from the specified hierarchy.
// analysisStructureId in this case is the cube ID
var def = hierarchyService.getMembers(hierarchy.analysisStructureId, {
    // specify the unique name since there's likely more than 1 hierarchy in
    // the cube
    "hierarchyUniqueName": hierarchy.uniqueName,
    // specify the deepest hierarchy level unique name
    "levelUniqueName": hierarchy.levels[hierarchy.levels.length - 1].uniqueName
});

// This example gets all the members with "Bike" in the caption. The caption
// is the text displayed to users, unlike the uniqueName.
def.done(function (members) {
    // loop through all the members
    members.forEach(function (member) {
        if (member.caption.indexOf("Bike") > -1) {
            // if the member has "Bike" in the caption,
            // load it into the values of the view parameter
            viewParameter.parameterValue.values.push(member.loadMemberValue());
        }
    });

    // Set the last modified time so this parameter takes precedence over any others
    viewParameter.invalidateParameterValueLastModifiedTime();

    // Update all the connected adapters with the newly modified values
    // Includes data visualizations and filter controls
    viewParameter.refreshAllAdapters();
});

3.5. SingleMember

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// Time dimensions have a little bit more going on, so in this example 
// we will be pulling the member value from an existing metric set, 
// and just to make it interesting, we will use a data retrieval service
// to get the metric set data

// The metric set ID, which can be found in the edit dialog from the Data Analysis Panel
var metricSetId = "4f0ed0b9-3a4e-4517-a000-a21e593ca0c3";

// Get the DataRetrievalService
var dataRetrievalService = this.getService("DataRetrievalService");
var viewService = this.getService("ViewService");

// Create a request object using the metric set ID
var request = new dundas.data.Request({
    "objectId": metricSetId,
    "requestData": dundas.Utility.createGuid(),
});

// Call getData from the service and wait for it to finish using its deferred object
var def = dataRetrievalService.getData(request);

// Show a loading message if the response takes some time
viewService.showLoadingRestCall(def);

// When we have the data, run the following
def.done(function (dataResults) {
    // Here we load the first member from the first row of the data result
    var memberValue = dataResults[0].cellset.rows[0].members[0].loadMemberValue();
   
    viewParameter.parameterValue.values = [memberValue];

    // Set the last modified time so this parameter takes precedence over any others
    viewParameter.invalidateParameterValueLastModifiedTime();

    // Update all the connected adapters with the newly modified values
    // Includes data visualizations and filter controls
    viewParameter.refreshAllAdapters();
});

3.6. RangeMember

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// Similar to the SingleMember example, we will pulling members from an existing 
// metric set since the RangeMember uses an upper member and a lower member

// The metric set ID, which can be found in the edit dialog from the Data Analysis Panel
var metricSetId = "4f0ed0b9-3a4e-4517-a000-a21e593ca0c3";

// Get the DataRetrievalService
var dataRetrievalService = this.getService("DataRetrievalService");
var viewService = this.getService("ViewService");

// Create a request object using the metric set ID
var request = new dundas.data.Request({
    "objectId": metricSetId,
    "requestData": dundas.Utility.createGuid()
});

// Call getData from the service and wait for it to finish using its deferred object
var def = dataRetrievalService.getData(request);

// Show a loading message if the response takes some time
viewService.showLoadingRestCall(def);

// When we have the data, run the following
def.done(function (dataResult) {
    // Load two members from the data result
    var lowerMemberValue = dataResult[0].cellset.rows[0].members[0].loadMemberValue();
    var upperMemberValue = dataResult[0].cellset.rows[9].members[0].loadMemberValue();
    
    // Since this is a member range, we have an upper member and lower member
    viewParameter.parameterValue.lowerBoundaryValue = lowerMemberValue;
    viewParameter.parameterValue.upperBoundaryValue = upperMemberValue;

    // Set the last modified time so this parameter takes precedence over any others
    viewParameter.invalidateParameterValueLastModifiedTime();

    // Update all the connected adapters with the newly modified values
    // Includes data visualizations and filter controls
    viewParameter.refreshAllAdapters();
});

3.7. RangeDateTime

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// A RangeDateTime parameter value will have an upper and lower value set
// similar to that of the RangeMember, but instead of member values inside 
// the upper and lower, there are just dates

// Create a date for the current time
var currentDateTime = new Date(Date.now());

// Create a date time object for this time one year ago
var oneYearAgo = new Date(Date.now());
oneYearAgo.addYears(-1);

// Assign the dates to their respective upper and lower values
viewParameter.parameterValue.lowerBoundaryValue = oneYearAgo;
viewParameter.parameterValue.upperBoundaryValue = currentDateTime;

// Set the last modified time so this parameter takes precedence over any others
viewParameter.invalidateParameterValueLastModifiedTime();

// Update all the connected adapters with the newly modified values
// Includes data visualizations and filter controls
viewParameter.refreshAllAdapters();

3.8. TokenValue

// In a view's (e.g., dashboard's) ready or load actions, use this rather than this.parentView:
var viewParameter = this.parentView.control.getViewParameterByName("viewParameter1");

// Remove all values and tokens from the parameter value.
viewParameter.parameterValue.clearTokens();
viewParameter.parameterValue.clearValues();

// We are going to set the lower token to Open Range Boundary
// and the upper range to End of Current Year (-1).
// If you know the ID of the token you want to use, you don't need to
// use the service. You can simply pass a new object into the token
// constructor with the desired properties.
// The dundas.constants contains some common token IDs:
viewParameter.parameterValue.lowerBoundaryToken = new dundas.data.ParameterToken({
    "id": dundas.constants.OPEN_RANGE_BOUNDARY_TOKEN_DEFINITION_ID,
    "caption": "Open Range Boundary"
});

// If we don't know the token ID, we can use the token service
var tokenService = view.getService("TokenService");

// This example uses time hierarchy tokens
var timeHierarchyDataType = dundas.data.CompatibleDataTypes.TIME_HIERARCHY;

// This example will use tokens that define the end of a range
var rangeEndTokenTypes = dundas.data.TokenDisplayTypes.DISPLAY_RANGE_END;

// Use the deferred object to wait for the token service to get the tokens from the server
var def = tokenService.getParameterTokens(timeHierarchyDataType, rangeEndTokenTypes);

// When request is done, use the result to get the desired token(s)
def.done(function (tokens) {
    // Store the token to modify later.
    var endCurrentYearToken = tokens.filter(function (token) {
        return token.caption == "End of current year";
    })[0];

    // Change the offset of the token
    endCurrentYearToken.offset = -1;

    // Set the upper token to the end of year token
    viewParameter.parameterValue.upperBoundaryToken = endCurrentYearToken;

    // Set the last modified time so this parameter takes precedence over any others
    viewParameter.invalidateParameterValueLastModifiedTime();

    // Update all the connected adapters with the newly modified values
    // Includes data visualizations and filter controls
    viewParameter.refreshAllAdapters();
});

4. Reset parameter values to "All" or "Default"

All the filters on the dashboard can be reset to "All" or "Default" values via a script. The script works for all types of filters.

this.parentView.control.viewParameters.forEach(function(viewParameter, index) {
    if (index != 0) { // skip the brush view parameter
        viewParameter.parameterValue.clearTokens();
        viewParameter.parameterValue.clearValues();
        viewParameter.parameterValue.token = new dundas.data.ParameterToken({
            // Use dundas.constants.ALL_TOKEN_DEFINITION_ID for "All" token
            "id": dundas.constants.DEFAULT_TOKEN_DEFINITION_ID,
            // Use "All" caption for All token
            "caption": "Default"
        });
        viewParameter.invalidateParameterValueLastModifiedTime();
        viewParameter.refreshAllAdapters();
    }
}); 

5. See also

Dundas Data Visualization, Inc.
500-250 Ferrand Drive
Toronto, ON, Canada
M3C 3G8

North America: 1.800.463.1492
International: 1.416.467.5100

Dundas Support Hours: 7am-6pm, ET, Mon-Fri