Limiting Date Filters to Datasource Date Range
Limiting Date Filters to Datasource Date Range By default, Sisense allows users to select any date in a dashboard date dimension filter, regardless of whether data exists for that date in the current dashboard datasource. The native Sisense date filter selection UI highlights the earliest and latest dates available via shading and color indications, but if a user selects a date outside this range, it is accepted as the desired filter from the user. While this behavior is generally the preferred behavior, there are cases where a dashboard creator might prefer the date filter to visually and programmatically reflect only the dates for which data exists in the datasource. In scenarios where the exact number of days in the filter range the data being viewed from is vital, such as when analyzing total date data coverage, performing per-day calculations, or simply ensuring that the visual filter UI accurately represents the actual data period being shown, the date filter should ideally be modified to only display date ranges that have corresponding data. This ensures that the filter not only serves as a control mechanism but also as an accurate visual cue of the available data's temporal range. The dashboard script presented below adds this custom functionality. It works by executing two custom JAQL queries (More documentation on custom script JAQL queries is available here) to fetch the sequentially earliest and latest dates from the datasource. These dates are then used as the bounds to restrict the filter. The dimensions used to fetch the date range and the dimension used to find the matching dashboard filter can be separate or identical dimensions, as they are separated in two variables. The script supports both common date filter formats, traditional "from-to" date ranges and filters that use a list of date members. Additionally, the approach can be extended to accommodate other filter types or JavaScript based actions beyond or not including filter modification when a filter's value falls outside the desired range. For more detail and an addition example see the article Redirect Users to Different Dashboards Based on Dashboard Filters. When a user selects a date that falls outside the available range of the datasource, the code below automatically adjusts the filter. It modifies the selection so that the filter is constrained to the earliest available date if the selected date is too early, or to the latest available date if it exceeds the maximum. If both boundaries are affected, the filter is adjusted on both ends to ensure that only dates with corresponding data are displayed. This solution provides a robust method to visually align your dashboard’s date filter with the actual data available, ensuring that users have a clear and accurate reference of the data period being analyzed. The full code implementing this functionality is provided below. (function () { const enableLogging = true; // Primary date dimension for the filter (change as needed) const dateDim = "[MainTable.Revenue Date (Calendar)]"; // JAQL dimension used to fetch the earliest/latest dates (change as needed) const jaqlDateDim = "[MainTable.Billing Date (Calendar)]"; /** * Simple logging function to enable or disable console logging. */ function log(...msgs) { if (enableLogging) { console.log(...msgs); } } /** * Formats a Date object as "YYYY-MM-DD". */ function formatDate(d) { const yyyy = d.getFullYear(); const mm = String(d.getMonth() + 1).padStart(2, "0"); const dd = String(d.getDate()).padStart(2, "0"); return `${yyyy}-${mm}-${dd}`; } /** * Finds the primary date filter (single-level) based on the defined dateDim. * * Note: * - If run within a dashboard script, the variable "dashboard" is already defined. * - If within a plugin, use prism.activeDashboard. * - If within a widget script, use widget.dashboard. */ function findSingleLevelDateFilter() { if (!dashboard.filters || !dashboard.filters.$$items) return null; return dashboard.filters.$$items.find(filterObj => !filterObj.isCascading && filterObj.jaql && filterObj.jaql.dim === dateDim ); } /** * Constructs a JAQL query to fetch a date from the datasource. * @param {string} direction - "asc" to fetch the earliest date, "desc" to fetch the latest. */ function buildDateQuery(direction) { return { datasource: dashboard.datasource, metadata: [ { jaql: { dim: jaqlDateDim, datatype: "datetime", level: "days", sort: direction } } ], count: 1 }; } /** * Executes an asynchronous HTTP request for the provided JAQL query. */ function runHTTP(jaql) { const $internalHttp = prism.$injector.has("base.factories.internalHttp") ? prism.$injector.get("base.factories.internalHttp") : null; const ajaxConfig = { url: `/api/datasources/${encodeURIComponent(jaql.datasource.title)}/jaql`, method: "POST", data: JSON.stringify(jaql), contentType: "application/json", dataType: "json", async: true, xhrFields: { withCredentials: true } }; return $internalHttp ? $internalHttp(ajaxConfig, false) : $.ajax(ajaxConfig); } /** * Adjusts the date filter so that its values fall within the datasource range. * For multi-valued filters (using a "members" array), out-of-range dates are removed. * For single-valued filters with "from" and "to" fields, each is updated if outside the available range. * * @param {Object} filterObj - The primary date filter object. * @param {Date} earliestDate - The earliest available date. * @param {Date} latestDate - The latest available date. */ function adjustDateFilterIfOutOfRange(filterObj, earliestDate, latestDate) { if (!filterObj || !filterObj.jaql || !filterObj.jaql.filter) return; const jaqlFilter = filterObj.jaql.filter; let adjustmentMade = false; // Adjust multi-valued filter (members). if (Array.isArray(jaqlFilter.members) && jaqlFilter.members.length > 0) { const originalCount = jaqlFilter.members.length; const validDates = jaqlFilter.members.filter(dateStr => { const d = new Date(dateStr); return !isNaN(d.valueOf()) && (!earliestDate || d >= earliestDate) && (!latestDate || d <= latestDate); }); if (validDates.length < originalCount) { jaqlFilter.members = validDates; adjustmentMade = true; log("Adjusted members filter to valid dates:", validDates); } } // Adjust "from" date if necessary. if (typeof jaqlFilter.from === "string") { const fromDate = new Date(jaqlFilter.from); if (earliestDate && fromDate < earliestDate) { jaqlFilter.from = formatDate(earliestDate); adjustmentMade = true; log("Adjusted 'from' date to:", jaqlFilter.from); } } // Adjust "to" date if necessary. if (typeof jaqlFilter.to === "string") { const toDate = new Date(jaqlFilter.to); if (latestDate && toDate > latestDate) { jaqlFilter.to = formatDate(latestDate); adjustmentMade = true; log("Adjusted 'to' date to:", jaqlFilter.to); } } if (adjustmentMade) { log("Date filter adjusted for dimension:", dateDim); } } /** * Retrieves the earliest and latest dates from the datasource, * then adjusts the primary date filter so that its values fall within that range. */ function updateDateFilter() { const queryEarliest = buildDateQuery("asc"); const queryLatest = buildDateQuery("desc"); Promise.all([runHTTP(queryEarliest), runHTTP(queryLatest)]) .then(([responseEarliest, responseLatest]) => { let earliestDate = null; let latestDate = null; if (responseEarliest && responseEarliest.data && responseEarliest.data.values?.length) { const eStr = responseEarliest.data.values[0][0].data; const dt = new Date(eStr); if (!isNaN(dt.valueOf())) { earliestDate = dt; log("Earliest date from datasource:", formatDate(dt)); } } if (responseLatest && responseLatest.data && responseLatest.data.values?.length) { const lStr = responseLatest.data.values[0][0].data; const dt = new Date(lStr); if (!isNaN(dt.valueOf())) { latestDate = dt; log("Latest date from datasource:", formatDate(dt)); } } const filterObj = findSingleLevelDateFilter(); if (!filterObj) { log("No primary date filter found; cannot adjust date filter."); return; } adjustDateFilterIfOutOfRange(filterObj, earliestDate, latestDate); }) .catch(err => { log("Error fetching datasource date range:", err); }); } // Call updateDateFilter() when filters change. dashboard.on('filterschanged', function () { updateDateFilter(); }); // Call updateDateFilter() on dashboard load dashboard.on('initialized', function () { updateDateFilter(); }); })();297Views1like0CommentsPassing Filters via URL Parameters for Dashboards with Separate Datasources
Sisense includes a native included feature and format for passing URL filters via URL parameters, as documented here. By default, this functionality copies filters in full, including the datasource parameter of the filter, and includes every filter automatically. It results in very long URL's, and includes many parameters that are not always required, as the full filter object is included. Previous Knowledge Base articles articles have discussed how similar behavior can be recreated customized via scripting for more flexible usage. However, those approaches applied only to member-type filters, excluding other filter types and multi-level dependent filters. The code shared below demonstrates a more flexible filter modification via URL modification approach. It includes both creating URL parameters and reading URL parameters for filter modification, whether this code is in a script or plugin. This method applies to all filter types and can be used to transfer filters between dashboards using different datasources. This code works in both dashboard and widget scripts as well as plugins. If your datasources use different dimension names, this code can be adopted to map and match the aligned dimensions.307Views1like0CommentsHow to Automatically Hide Accordion Widgets When Clicking on Tabber (Linux)
How to Automatically Hide Accordion Widgets When Clicking Outside the Accordion Window (Linux) Introduction This article addresses the specific scenario where accordion widgets remain visible even after interacting with other interface elements, such as tabber widgets, in a dashboard environment. Step-by-Step Guide Integrate a widget Script in the widget edit mode > click the 3 dots menu > Edit Script: widget.on("ready", function(w, e) { var tabs = document.querySelectorAll(".listDefaultCSS > span.listItemDefaultCSS, .listItemContainer > span.listItemDefaultCSS, .listItemContainer.selected > span.listItemDefaultCSS"); tabs.forEach(function(tab) { tab.addEventListener("click", function(e) { var accordions = document.querySelectorAll(".bk-accordion"); var arrows = document.querySelectorAll(".bk-arrow"); accordions.forEach(function(accrd) { if (accrd.style.opacity == "1") { accrd.style.opacity = "0"; accrd.style.padding = "0"; accrd.style.height = "0"; } }); arrows.forEach(function(arr) { if (arr.style.opacity == "1") { arr.style.opacity = "0"; } }); }); }); }); This script will detect clicks on the tabber widgets and hide any visible accordion windows by setting their opacity, padding, and height to zero. After adding the script, navigate through your dashboard to ensure that accordion widgets hide as expected when clicking on a tabber widget or other areas. [ALT Text: A data visualization dashboard displaying a bar graph titled "Profit per Product." The graph shows profit values for different products with values reaching up to 10,000. The total EU profit is indicated as 23,36K, with a profit rate of 49.81%. Tabs for additional analysis are visible at the top.] Conclusion By incorporating the provided dashboard script, users can enhance their user interface experience by ensuring accordion widgets automatically hide when interacting with other dashboard elements. Despite the current design limitations regarding the accordion's position, the script offers a viable solution to improve dashboard interactions. Disclaimer: This post outlines a potential custom workaround for a specific use case or provides instructions regarding a specific task. The solution may not work in all scenarios or Sisense versions, so we strongly recommend testing it in your environment before deployment. If you need further assistance with this please let us know.178Views1like0CommentsCustom sort for Bar and Column Chart
Custom sort for Bar and Column Chart Question: I have seen several posts of people asking if there is a simple way to apply custom sorts for car and column charts, and until recently, I have been using the community customBarColumnChart Plugin, which is not supported anymore, and also not working correctly in the latest version of Sisense cloud. Not sure why this cannot become a standard feature within the system, as there seem to be a lot of requests for this functionality. Answer: The following widget scripts will allow you to sort categories in a bar/column chart. You can change the order of items in sortOrder to change the order. They cater to when you want to sort by a Break By, or when you want to sort by Categories with no Break By. BREAK BY: widget.on('processresult', (w, args) => { var sortOrder = ['Yellow', 'Black', 'Red', 'Blue ', 'Gold', 'Silver'] args.result.series.sort(function (a, b) { return sortOrder.indexOf(a.name) - sortOrder.indexOf(b.name) }) }) The configuration is also attached in a screenshot below: ALT Text: A bar chart displaying total order quantities by region. Two regions are represented: Europe and USA. Each region has bars segmented by color: yellow, blue, black, gold, red, and silver. The chart highlights comparisons in order quantities between the two regions, with specific quantities not indicated in the image. CATEGORIES: If you're aiming to sort by the Categories directly, then you can use the following instead: widget.on('processresult', (w, args) => { var sortOrder = ['USA', 'Europe'] args.result.series[0].data.sort(function (a, b) { return sortOrder.indexOf(a.selectionData[0]) - sortOrder.indexOf(b.selectionData[0]) }) args.result.xAxis.categories.sort(function (a, b) { return sortOrder.indexOf(a) - sortOrder.indexOf(b) }) }) This configuration looks like this: ALT text: Bar chart comparing total order quantity between the USA and Europe. The USA has a higher total order quantity than Europe, with both categories represented in dark blue bars on a white background. This was tested using Sample Retail. Let me know how it goes for you in the comments! Check out this related content: Academy Documentation2.2KViews3likes4CommentsCustomizing Upper Label (PlotBands) Labels in Sisense Column Chart Widgets for Long Category Labels
Sisense allows customization of chart settings through Highchart option configurations, as documented in this community post leveraging the Highcharts settings of the widget using Sisense widget scripting capabilities. When creating Sisense column chart widgets with two fields in the "Categories" panel, an upper label is created. These labels can be long, requiring management of lengthy category labels in column chart widgets. In the Highcharts library terminology, these upper labels are called plotBands. This article explains how to modify plotBand label settings in Sisense column chart widgets to support long upper category labels by adjusting font size and enabling multi-line labels. This method demonstrates another use of the beforeviewloaded event to adjust Highcharts configurations in a Sisense widget, similar to adjusting offset sizes in pie charts as discussed in this article.658Views1like0CommentsCustomizing the Offset Size of Selected Categories in Sisense Pie Chart Widgets
In Sisense, pie chart widgets, including the various pie chart style options such as donut charts, are a common way to visualize data. By default, when a user selects a category within a pie chart, that slice "pops out" to highlight the selection. This article explains how to customize the offset size of selected categories in Sisense pie chart widgets by leveraging Highcharts settings of the widget using Sisense widget scripting capabilities.490Views2likes0CommentsLimiting Date Range Filters in Sisense Dashboards
Wide date ranges in Sisense dashboards can lead to performance issues, especially when using live models or querying large datasets. For live data models, large queries increase costs as more data is pulled from the data warehouse. For Elasticubes, this can cause performance bottlenecks. To avoid these issues, here is a quick solution to "limit" the date range users can select, ensuring both cost-efficiency and smooth performance. Read more to find out how!639Views1like0CommentsDynamic Widget Scripts
Download: GitHub Link Version: 1.0.0 Introduction: This article explains how to install the plug-in and how to interact with the js and configuration file. Purpose/Benefits: This plug-in will add or change change the current script applied to widgets on a dashboard to a script specified by the user. The user can also specify different scripts to apply to a widget depending on the user's group. How To Install and Configure the Plug-In Step 1 - Add The Plugin: You can download the plug-in using the link above. Once dowloaded, unzip the file. Within the Admin tab, navigate to System Management >> File Management >> plugins and upload the 'DynamicWidgetScripts' folder into the directory. Step 2 - Decide if You Will Use Dynamic Group Functionality: This plug-in allows for dynamic functionality to apply different scripts based on a user's group. This functionality is ON by default. If you would like to use this functionality please proceed to step 3. If you do not want to enable this feature, within the plug-in folder, in the 'changescripts_allwidgets.6.js' file, set the 'useGroups' variable to false. Step 3 - Setup the Config File: Within the plug-in folder ('DynamicWidgetScripts') open the 'config.js' file. Set the group name(s) to be effected by the plug-in under the 'groupName' variable as a string (do not include the [ ] characters). You may create and add multiple config objects into the config file, depending on the number of groups. Step 4 - Setup the Widget Script: If you ARE using Dynamic Groups In the 'config.js' file, within the 'defaultConfig' object, under 'wScript', specify the script to be applied to the widgets. If you ARE NOT using Dynamic Groups In the 'config.js' file, under the 'wScript' variable NOT within the 'defaultConfig' object, specify the script to be applied to the widgets. Example Script: The config file comes with a default script that will be applied to your widgets. e.result.plotOptions.series.dataLabels.style.color = 'green'; //change data label color e.result.plotOptions.series.dataLabels.style.fontSize = '12px'; //change data label size e.result.plotOptions.series.dataLabels.style.fontWeight = 'bold'; //bold data labels e.result.plotOptions.series.dataLabels.allowOverlap = true; //allow data label overlap Additional widget settings can be changed apart from what is listed here. For reference as to what settings can be adjusted, please see HighCharts API documentation here: https://api.highcharts.com/highcharts/. Step 4 - Apply the changes You can apply the changes by simply refreshing your add-ons page within the admin tab and then refreshing the dashboard. In-Action Example: Group 1 View: Group 2 View: Notes (Version 1.0.0): You can add multiple groups and scripts (one per group). Release Notes: 23-December-2021: Initial Release1.6KViews1like0Comments