Im working on a html dashboard to interact with a kvstore (save and delete records)
What Im struggling with is getting the earliest and latest from a timerange picker which i want to save to the kvstore.
All other fields are saved perfectly, but i just cant get the values from the timerange picker.
Where did i go wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Alert Disabling</title>
<link rel="shortcut icon" href="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/img/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/build/css/bootstrap-enterprise.css" />
<link rel="stylesheet" type="text/css" href="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/css/build/pages/dashboard-simple-bootstrap.min.css" />
</head>
<body class="simplexml preload locale-en" data-splunk-version="6.5.1612" data-splunk-product="enterprise">
<!--
BEGIN LAYOUT
This section contains the layout for the dashboard. Splunk uses proprietary
styles in <div> tags, similar to Bootstrap's grid system.
-->
<header>
<a class="navSkip" href="#navSkip" tabindex="1">Screen reader users, click here to skip the navigation bar</a>
<div class="header splunk-header">
<div id="placeholder-splunk-bar">
<a href="/en-US/app/launcher/home" class="brand" title="splunk > listen to your data">splunk<strong>></strong></a>
</div>
<div id="placeholder-app-bar"></div>
</div>
<a id="navSkip"></a>
</header>
<div class="dashboard-body container-fluid main-section-body" data-role="main">
<h2>Alert disabling</h2>
<p>
This page makes it possible to disable alerts for a specific device.<br/>
<b>Next update in <span id='timeleft'></span> minutes @ <span id='time'></span></b><br/>
Changes needs to be saved before that time, and will be effective 15 minutes after that time.
</p>
<form id="formAlertsEnabled">
<div class="fieldset">
<div class="input input-dropdown" id="input1">
<label>Customer</label>
</div>
<div class="input input-dropdown" id="input2">
<label>Device</label>
</div>
<div class="input input-timerangepicker" id="input3">
<label> </label>
</div>
<div class="form-submit" id="search_btn">
<button id="disableButton">Disable Alerts</button>
</div>
</div>
<div>
<div class="input input-dropdown" id="input7">
<label>Select a disabled device to enable</label>
</div>
<div><button id="deleteRecord">Enable Alerts</button></div>
</div>
</form>
<div id="row1" class="dashboard-row dashboard-row1">
<div id="panel1" class="dashboard-cell" style="width: 100%;">
<div class="dashboard-panel clearfix">
<div class="panel-element-row">
<div id="element1" class="dashboard-element table" style="width: 100%">
<div class="panel-head">
<h3>Alerts Disabled For Following Devices - Alow up to 10 minutes for this table to update</h3>
</div>
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
END LAYOUT
-->
<script src="/en-US/config?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/js/i18n.js"></script>
<script src="/en-US/i18ncatalog?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/build/simplexml/index.js"></script>
<script src="{{SPLUNKWEB_URL_PREFIX}}/static/js/build/simplexml.min/config.js"></script>
<script type="text/javascript">
// <![CDATA[
require.config({
baseUrl: "{{SPLUNKWEB_URL_PREFIX}}/static/js",
waitSeconds: 0 // Disable require.js load timeout
});
//
// LIBRARY REQUIREMENTS
//
// In the require function, we include the necessary libraries and modules for
// the HTML dashboard. Then, we pass variable names for these libraries and
// modules as function parameters, in order.
//
// When you add libraries or modules, remember to retain this mapping order
// between the library or module and its function parameter. You can do this by
// adding to the end of these lists, as shown in the commented examples below.
require([
"splunkjs/mvc",
"splunkjs/mvc/utils",
"splunkjs/mvc/tokenutils",
"underscore",
"jquery",
"splunkjs/mvc/simplexml",
"splunkjs/mvc/layoutview",
"splunkjs/mvc/simplexml/dashboardview",
"splunkjs/mvc/simplexml/dashboard/panelref",
"splunkjs/mvc/simplexml/element/chart",
"splunkjs/mvc/simplexml/element/event",
"splunkjs/mvc/simplexml/element/html",
"splunkjs/mvc/simplexml/element/list",
"splunkjs/mvc/simplexml/element/map",
"splunkjs/mvc/simplexml/element/single",
"splunkjs/mvc/simplexml/element/table",
"splunkjs/mvc/simplexml/element/visualization",
"splunkjs/mvc/simpleform/formutils",
"splunkjs/mvc/simplexml/eventhandler",
"splunkjs/mvc/simplexml/searcheventhandler",
"splunkjs/mvc/simpleform/input/dropdown",
"splunkjs/mvc/simpleform/input/radiogroup",
"splunkjs/mvc/simpleform/input/linklist",
"splunkjs/mvc/simpleform/input/multiselect",
"splunkjs/mvc/simpleform/input/checkboxgroup",
"splunkjs/mvc/simpleform/input/text",
"splunkjs/mvc/simpleform/input/timerange",
"splunkjs/mvc/simpleform/input/submit",
"splunkjs/mvc/searchmanager",
"splunkjs/mvc/savedsearchmanager",
"splunkjs/mvc/postprocessmanager",
"splunkjs/mvc/simplexml/urltokenmodel"
// Add comma-separated libraries and modules manually here, for example:
// ..."splunkjs/mvc/simplexml/urltokenmodel",
// "splunkjs/mvc/tokenforwarder"
],
function(
mvc,
utils,
TokenUtils,
_,
$,
DashboardController,
LayoutView,
Dashboard,
PanelRef,
ChartElement,
EventElement,
HtmlElement,
ListElement,
MapElement,
SingleElement,
TableElement,
VisualizationElement,
FormUtils,
EventHandler,
SearchEventHandler,
DropdownInput,
RadioGroupInput,
LinkListInput,
MultiSelectInput,
CheckboxGroupInput,
TextInput,
TimeRangeInput,
SubmitButton,
SearchManager,
SavedSearchManager,
PostProcessManager,
UrlTokenModel
// Add comma-separated parameter names here, for example:
// ...UrlTokenModel,
// TokenForwarder
) {
var pageLoading = true;
//
// TOKENS
//
// Create token namespaces
var urlTokenModel = new UrlTokenModel();
mvc.Components.registerInstance('url', urlTokenModel);
var defaultTokenModel = mvc.Components.get('default', {create: true});
var submittedTokenModel = mvc.Components.get('submitted', {create: true});
urlTokenModel.on('url:navigate', function() {
defaultTokenModel.set(urlTokenModel.toJSON());
if (!_.isEmpty(urlTokenModel.toJSON()) && !_.all(urlTokenModel.toJSON(), _.isUndefined)) {
submitTokens();
} else {
submittedTokenModel.clear();
}
});
// Initialize tokens
defaultTokenModel.set(urlTokenModel.toJSON());
function submitTokens() {
// Copy the contents of the defaultTokenModel to the submittedTokenModel and urlTokenModel
FormUtils.submitForm({ replaceState: pageLoading });
}
function setToken(name, value) {
defaultTokenModel.set(name, value);
submittedTokenModel.set(name, value);
}
function unsetToken(name) {
defaultTokenModel.unset(name);
submittedTokenModel.unset(name);
}
//
// SEARCH MANAGERS
//
var search1 = new SearchManager({
"id": "search1",
"search": "index=genericstats sourcetype=stats | stats latest(customername) as customername by customer",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search2 = new SearchManager({
"id": "search2",
"search": "index=genericstats sourcetype=stats customer=$customer$ | lookup alert_disable hostname | stats latest(hostname) as hostname latest(alert_enabled) as alert_enabled by id | where NOT alert_enabled = \"false\"",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search3 = new SearchManager({
"id": "search3",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table KeyID, hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
var search4 = new SearchManager({
"id": "search4",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as Hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table Hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
//
// SPLUNK LAYOUT
//
$('header').remove();
new LayoutView({"hideChrome": false, "hideSplunkBar": false, "hideAppBar": false, "hideFooter": false})
.render()
.getContainerElement()
.appendChild($('.dashboard-body')[0]);
//
// DASHBOARD EDITOR
//
new Dashboard({
id: 'dashboard',
el: $('.dashboard-body'),
showTitle: true,
editable: true
}, {tokens: true}).render();
//
// VIEWS: VISUALIZATION ELEMENTS
//
var element1 = new TableElement({
"id": "element1",
"drilldown": "none",
"rowNumbers": "undefined",
"wrap": "undefined",
"managerid": "search4",
"el": $('#element1')
}, {tokens: true, tokenNamespace: "submitted"}).render();
//
// VIEWS: FORM INPUTS
//
var input1 = new DropdownInput({
"id": "input1",
"choices": [],
"labelField": "customername",
"valueField": "customer",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.customer$",
"managerid": "search1",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
var input2 = new DropdownInput({
"id": "input2",
"choices": [],
"labelField": "hostname",
"valueField": "hostname",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.id$",
"managerid": "search2",
"el": $('#input2')
}, {tokens: true}).render();
input2.on("change", function(newValue) {
FormUtils.handleValueChange(input2);
});
var mypresetsettings={
showPresets:false,
showPresetsRealTime:false,
showPresetsRealTimeOnly:false,
showPresetsRelative:false,
showPresetsAllTime:false,
showCustom:true, // <-- indicates whether or not to show other panels then the presets panel
showCustomRealTime:false,
showCustomRelative:false,
showCustomDate:false, // Only show CustomDate
showCustomDateTime:true,
showCustomDateTimeSince:false,
showCustomAdvanced:false,
enableCustomAdvancedRealTime:false
};
var input3 = new TimeRangeInput({
"id": "input3",
"default": {"latest_time": "-24h@h", "earliest_time": "now"},
"earliest_time": "now",
"latest_time": "-24h@h",
"dialogOptions": mypresetsettings,
"el": $('#input3')
}, {tokens: true}).render();
input3.on("change", function(newValue) {
FormUtils.handleValueChange(input3);
});
var input7 = new DropdownInput({
"id": "input7",
"choices": [],
"labelField": "hostname",
"valueField": "KeyID",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.KeyID$",
"managerid": "search3",
"el": $('#input7')
}, {tokens: true}).render();
input7.on("change", function(newValue) {
FormUtils.handleValueChange(input7);
});
//
// SERVICE OBJECT
//
// Create a service object using the Splunk SDK for JavaScript
// to send REST requests
var service = mvc.createService({ owner: "nobody" });
//
// DELETE BUTTON
//
// Call this function when the Delete Record button is clicked
$("#deleteRecord").click(function() {
// Get the value of the key ID field
var tokens = mvc.Components.get("default");
var form_keyid = tokens.get("KeyID");
// Delete the record that corresponds to the key ID using
// the del method to send a DELETE request
// to the storage/collections/data/{collection}/ endpoint
service.del("/servicesNS/nobody/<app_name>/storage/collections/data/alert_disable/" + encodeURIComponent(form_keyid))
.done(function() {
// Run the search again to update the table
search3.startSearch();
search4.startSearch();
});
return false;
});
//
// SUBMIT FORM DATA
//
//var submit = new SubmitButton({
// id: 'submit',
// el: $('#search_btn')
//}, {tokens: true}).render();
//submit.on("submit", function() {
$("#disableButton").click(function() {
submitTokens();
// When the Submit button is clicked, get all the form fields by accessing token values
var tokens = mvc.Components.get("default");
var form_hostname = tokens.get("id");
var form_earliest = tokens.get("earliest");
var form_latest = tokens.get("latest");
var form_enabled = "false";
// Create a dictionary to store the field names and values
var record = {
"hostname": form_hostname,
"alert_enabled": form_enabled,
"earliest": form_earliest,
"latest": form_latest
};
// Use the request method to send a REST POST request
// to the storage/collections/data/{collection}/ endpoint
service.request(
"/servicesNS/nobody/<app_name>/storage/collections/data/alert_disable/",
"POST",
null,
null,
JSON.stringify(record),
{"Content-Type": "application/json"},
null)
.done(function() {
// Run the search again to update the table
search2.startSearch();
search3.startSearch();
search4.startSearch();
// Clear the form fields
// $("#formAlertsEnabled input[type=text]").val("");
});
});
// Initialize time tokens to default
if (!defaultTokenModel.has('earliest') && !defaultTokenModel.has('latest')) {
defaultTokenModel.set({ earliest: '0', latest: '' });
}
if (!_.isEmpty(urlTokenModel.toJSON())){
submitTokens();
}
//
// DASHBOARD READY
//
DashboardController.ready();
pageLoading = false;
}
);
// ]]>
</script>
</body>
</html>
Apparently i had set set properties earliest_time and latest_time for input3 wrong.
This is working:
<!DOCTYPE html>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body class="simplexml preload locale-en" data-splunk-version="6.5.1612" data-splunk-product="enterprise">
<!--
BEGIN LAYOUT
This section contains the layout for the dashboard. Splunk uses proprietary
styles in <div> tags, similar to Bootstrap's grid system.
-->
<header>
<a class="navSkip" href="#navSkip" tabindex="1">Screen reader users, click here to skip the navigation bar</a>
<div class="header splunk-header">
<div id="placeholder-splunk-bar">
<a href="/en-US/app/launcher/home" class="brand" title="splunk > listen to your data">splunk<strong>></strong></a>
</div>
<div id="placeholder-app-bar"></div>
</div>
<a id="navSkip"></a>
</header>
<div class="dashboard-body container-fluid main-section-body" data-role="main">
<h2>Alert disabling</h2>
<p>
This page makes it possible to disable alerts for a specific device.<br/>
<b>Next update in <span id='timeleft'></span> minutes @ <span id='time'></span></b><br/>
Changes needs to be saved before that time, and will be effective 15 minutes after that time.
</p>
<form id="formAlertsEnabled">
<div class="fieldset">
<div class="input input-dropdown" id="input1">
<label>Customer</label>
</div>
<div class="input input-dropdown" id="input2">
<label>Device</label>
</div>
<div class="input input-timerangepicker" id="input3">
<label> </label>
</div>
<div class="form-submit" id="search_btn">
<button id="disableButton">Disable Alerts</button>
</div>
</div>
<div>
<div class="input input-dropdown" id="input7">
<label>Select a disabled device to enable</label>
</div>
<div><button id="deleteRecord">Enable Alerts</button></div>
</div>
</form>
<div id="row1" class="dashboard-row dashboard-row1">
<div id="panel1" class="dashboard-cell" style="width: 100%;">
<div class="dashboard-panel clearfix">
<div class="panel-element-row">
<div id="element1" class="dashboard-element table" style="width: 100%">
<div class="panel-head">
<h3>Alerts Disabled For Following Devices - Alow up to 10 minutes for this table to update</h3>
</div>
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
END LAYOUT
-->
<script src="/en-US/config?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/js/i18n.js"></script>
<script src="/en-US/i18ncatalog?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/build/simplexml/index.js"></script>
<script src="{{SPLUNKWEB_URL_PREFIX}}/static/js/build/simplexml.min/config.js"></script>
<script type="text/javascript">
// <![CDATA[
require.config({
baseUrl: "{{SPLUNKWEB_URL_PREFIX}}/static/js",
waitSeconds: 0 // Disable require.js load timeout
});
//
// LIBRARY REQUIREMENTS
//
// In the require function, we include the necessary libraries and modules for
// the HTML dashboard. Then, we pass variable names for these libraries and
// modules as function parameters, in order.
//
// When you add libraries or modules, remember to retain this mapping order
// between the library or module and its function parameter. You can do this by
// adding to the end of these lists, as shown in the commented examples below.
require([
"splunkjs/mvc",
"splunkjs/mvc/utils",
"splunkjs/mvc/tokenutils",
"underscore",
"jquery",
"splunkjs/mvc/simplexml",
"splunkjs/mvc/layoutview",
"splunkjs/mvc/simplexml/dashboardview",
"splunkjs/mvc/simplexml/dashboard/panelref",
"splunkjs/mvc/simplexml/element/chart",
"splunkjs/mvc/simplexml/element/event",
"splunkjs/mvc/simplexml/element/html",
"splunkjs/mvc/simplexml/element/list",
"splunkjs/mvc/simplexml/element/map",
"splunkjs/mvc/simplexml/element/single",
"splunkjs/mvc/simplexml/element/table",
"splunkjs/mvc/simplexml/element/visualization",
"splunkjs/mvc/simpleform/formutils",
"splunkjs/mvc/simplexml/eventhandler",
"splunkjs/mvc/simplexml/searcheventhandler",
"splunkjs/mvc/simpleform/input/dropdown",
"splunkjs/mvc/simpleform/input/radiogroup",
"splunkjs/mvc/simpleform/input/linklist",
"splunkjs/mvc/simpleform/input/multiselect",
"splunkjs/mvc/simpleform/input/checkboxgroup",
"splunkjs/mvc/simpleform/input/text",
"splunkjs/mvc/simpleform/input/timerange",
"splunkjs/mvc/simpleform/input/submit",
"splunkjs/mvc/searchmanager",
"splunkjs/mvc/savedsearchmanager",
"splunkjs/mvc/postprocessmanager",
"splunkjs/mvc/simplexml/urltokenmodel"
// Add comma-separated libraries and modules manually here, for example:
// ..."splunkjs/mvc/simplexml/urltokenmodel",
// "splunkjs/mvc/tokenforwarder"
],
function(
mvc,
utils,
TokenUtils,
_,
$,
DashboardController,
LayoutView,
Dashboard,
PanelRef,
ChartElement,
EventElement,
HtmlElement,
ListElement,
MapElement,
SingleElement,
TableElement,
VisualizationElement,
FormUtils,
EventHandler,
SearchEventHandler,
DropdownInput,
RadioGroupInput,
LinkListInput,
MultiSelectInput,
CheckboxGroupInput,
TextInput,
TimeRangeInput,
SubmitButton,
SearchManager,
SavedSearchManager,
PostProcessManager,
UrlTokenModel
// Add comma-separated parameter names here, for example:
// ...UrlTokenModel,
// TokenForwarder
) {
var pageLoading = true;
//
// TOKENS
//
// Create token namespaces
var urlTokenModel = new UrlTokenModel();
mvc.Components.registerInstance('url', urlTokenModel);
var defaultTokenModel = mvc.Components.get('default', {create: true});
var submittedTokenModel = mvc.Components.get('submitted', {create: true});
urlTokenModel.on('url:navigate', function() {
defaultTokenModel.set(urlTokenModel.toJSON());
if (!_.isEmpty(urlTokenModel.toJSON()) && !_.all(urlTokenModel.toJSON(), _.isUndefined)) {
submitTokens();
} else {
submittedTokenModel.clear();
}
});
// Initialize tokens
defaultTokenModel.set(urlTokenModel.toJSON());
function submitTokens() {
// Copy the contents of the defaultTokenModel to the submittedTokenModel and urlTokenModel
FormUtils.submitForm({ replaceState: pageLoading });
}
function setToken(name, value) {
defaultTokenModel.set(name, value);
submittedTokenModel.set(name, value);
}
function unsetToken(name) {
defaultTokenModel.unset(name);
submittedTokenModel.unset(name);
}
//
// SEARCH MANAGERS
//
var search1 = new SearchManager({
"id": "search1",
"search": "index=genericstats sourcetype=stats | stats latest(customername) as customername by customer",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search2 = new SearchManager({
"id": "search2",
"search": "index=genericstats sourcetype=stats customer=$customer$ | lookup alert_disable hostname | stats latest(hostname) as hostname latest(alert_enabled) as alert_enabled by id | where NOT alert_enabled = \"false\"",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search3 = new SearchManager({
"id": "search3",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table KeyID, hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
var search4 = new SearchManager({
"id": "search4",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as Hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table Hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
//
// SPLUNK LAYOUT
//
$('header').remove();
new LayoutView({"hideChrome": false, "hideSplunkBar": false, "hideAppBar": false, "hideFooter": false})
.render()
.getContainerElement()
.appendChild($('.dashboard-body')[0]);
//
// DASHBOARD EDITOR
//
new Dashboard({
id: 'dashboard',
el: $('.dashboard-body'),
showTitle: true,
editable: true
}, {tokens: true}).render();
//
// VIEWS: VISUALIZATION ELEMENTS
//
var element1 = new TableElement({
"id": "element1",
"drilldown": "none",
"rowNumbers": "undefined",
"wrap": "undefined",
"managerid": "search4",
"el": $('#element1')
}, {tokens: true, tokenNamespace: "submitted"}).render();
//
// VIEWS: FORM INPUTS
//
var input1 = new DropdownInput({
"id": "input1",
"choices": [],
"labelField": "customername",
"valueField": "customer",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.customer$",
"managerid": "search1",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
var input2 = new DropdownInput({
"id": "input2",
"choices": [],
"labelField": "hostname",
"valueField": "hostname",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.id$",
"managerid": "search2",
"el": $('#input2')
}, {tokens: true}).render();
input2.on("change", function(newValue) {
FormUtils.handleValueChange(input2);
});
var mypresetsettings={
showPresets:false,
showPresetsRealTime:false,
showPresetsRealTimeOnly:false,
showPresetsRelative:false,
showPresetsAllTime:false,
showCustom:true, // <-- indicates whether or not to show other panels then the presets panel
showCustomRealTime:false,
showCustomRelative:false,
showCustomDate:false, // Only show CustomDate
showCustomDateTime:true,
showCustomDateTimeSince:false,
showCustomAdvanced:false,
enableCustomAdvancedRealTime:false
};
var input3 = new TimeRangeInput({
"id": "input3",
"default": {"latest_time": "-24h@h", "earliest_time": "now"},
"earliest_time": "$form.field3.earliest$",
"latest_time": "$form.field3.latest$",
"dialogOptions": mypresetsettings,
"el": $('#input3')
}, {tokens: true}).render();
input3.on("change", function(newValue) {
FormUtils.handleValueChange(input3);
});
var input7 = new DropdownInput({
"id": "input7",
"choices": [],
"labelField": "hostname",
"valueField": "KeyID",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.KeyID$",
"managerid": "search3",
"el": $('#input7')
}, {tokens: true}).render();
input7.on("change", function(newValue) {
FormUtils.handleValueChange(input7);
});
//
// SERVICE OBJECT
//
// Create a service object using the Splunk SDK for JavaScript
// to send REST requests
var service = mvc.createService({ owner: "nobody" });
//
// DELETE BUTTON
//
// Call this function when the Delete Record button is clicked
$("#deleteRecord").click(function() {
// Get the value of the key ID field
var tokens = mvc.Components.get("default");
var form_keyid = tokens.get("KeyID");
// Delete the record that corresponds to the key ID using
// the del method to send a DELETE request
// to the storage/collections/data/{collection}/ endpoint
service.del("/servicesNS/nobody/<app>/storage/collections/data/alert_disable/" + encodeURIComponent(form_keyid))
.done(function() {
// Run the search again to update the table
search3.startSearch();
search4.startSearch();
});
return false;
});
//
// SUBMIT FORM DATA
//
//var submit = new SubmitButton({
// id: 'submit',
// el: $('#search_btn')
//}, {tokens: true}).render();
//submit.on("submit", function() {
$("#disableButton").click(function() {
submitTokens();
// When the Submit button is clicked, get all the form fields by accessing token values
var tokens = mvc.Components.get("default");
var form_hostname = tokens.get("id");
var form_timeframe_start = tokens.get("field3.earliest");
var form_timeframe_end = tokens.get("field3.latest");
var form_enabled = "false";
console.log(form_timeframe_start);
console.log(form_timeframe_end);
// Create a dictionary to store the field names and values
var record = {
"hostname": form_hostname,
"alert_enabled": form_enabled,
"start": form_timeframe_start,
"end": form_timeframe_end
};
// Use the request method to send a REST POST request
// to the storage/collections/data/{collection}/ endpoint
service.request(
"/servicesNS/nobody/<app>/storage/collections/data/alert_disable/",
"POST",
null,
null,
JSON.stringify(record),
{"Content-Type": "application/json"},
null)
.done(function() {
// Run the search again to update the table
search2.startSearch();
search3.startSearch();
search4.startSearch();
// Clear the form fields
// $("#formAlertsEnabled input[type=text]").val("");
});
});
// Initialize time tokens to default
if (!defaultTokenModel.has('earliest') && !defaultTokenModel.has('latest')) {
defaultTokenModel.set({ earliest: '0', latest: '' });
}
if (!_.isEmpty(urlTokenModel.toJSON())){
submitTokens();
}
//
// DASHBOARD READY
//
DashboardController.ready();
pageLoading = false;
}
);
// ]]>
</script>
</body>
</html>
@polymorphic, since this is a HTML Dashboard, the line 195 of code posted here is already setting submittedTokenModel
i.e.,
var submittedTokenModel = mvc.Components.get('submitted', {create: true});
You need to directly access using submittedTokenModel
which is already present on click of your disable button.
var form_earliest = submittedTokenModel.get("form.input3.earliest");
var form_latest = submittedTokenModel.get("form.input3.latest");
Following is a way to test
only the Time Input Tokens on Change of Earliest Time
:
submittedTokenModel.on("change:form.input3.earliest",function(newValue,value,option){
var form_earliest = submittedTokenModel.get("form.input3.earliest");
var form_latest = submittedTokenModel.get("form.input3.latest");
console.log("form_earliest: ",form_earliest);
console.log("form_latest: ",form_latest);
});
Apparently i had set set properties earliest_time and latest_time for input3 wrong.
This is working:
<!DOCTYPE html>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body class="simplexml preload locale-en" data-splunk-version="6.5.1612" data-splunk-product="enterprise">
<!--
BEGIN LAYOUT
This section contains the layout for the dashboard. Splunk uses proprietary
styles in <div> tags, similar to Bootstrap's grid system.
-->
<header>
<a class="navSkip" href="#navSkip" tabindex="1">Screen reader users, click here to skip the navigation bar</a>
<div class="header splunk-header">
<div id="placeholder-splunk-bar">
<a href="/en-US/app/launcher/home" class="brand" title="splunk > listen to your data">splunk<strong>></strong></a>
</div>
<div id="placeholder-app-bar"></div>
</div>
<a id="navSkip"></a>
</header>
<div class="dashboard-body container-fluid main-section-body" data-role="main">
<h2>Alert disabling</h2>
<p>
This page makes it possible to disable alerts for a specific device.<br/>
<b>Next update in <span id='timeleft'></span> minutes @ <span id='time'></span></b><br/>
Changes needs to be saved before that time, and will be effective 15 minutes after that time.
</p>
<form id="formAlertsEnabled">
<div class="fieldset">
<div class="input input-dropdown" id="input1">
<label>Customer</label>
</div>
<div class="input input-dropdown" id="input2">
<label>Device</label>
</div>
<div class="input input-timerangepicker" id="input3">
<label> </label>
</div>
<div class="form-submit" id="search_btn">
<button id="disableButton">Disable Alerts</button>
</div>
</div>
<div>
<div class="input input-dropdown" id="input7">
<label>Select a disabled device to enable</label>
</div>
<div><button id="deleteRecord">Enable Alerts</button></div>
</div>
</form>
<div id="row1" class="dashboard-row dashboard-row1">
<div id="panel1" class="dashboard-cell" style="width: 100%;">
<div class="dashboard-panel clearfix">
<div class="panel-element-row">
<div id="element1" class="dashboard-element table" style="width: 100%">
<div class="panel-head">
<h3>Alerts Disabled For Following Devices - Alow up to 10 minutes for this table to update</h3>
</div>
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
END LAYOUT
-->
<script src="/en-US/config?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/js/i18n.js"></script>
<script src="/en-US/i18ncatalog?autoload=1"></script>
<script src="/en-US/static/@D6A26182984E9D8CCE322353620B54C14CC0669897C065AE4A74F322445E60DB/build/simplexml/index.js"></script>
<script src="{{SPLUNKWEB_URL_PREFIX}}/static/js/build/simplexml.min/config.js"></script>
<script type="text/javascript">
// <![CDATA[
require.config({
baseUrl: "{{SPLUNKWEB_URL_PREFIX}}/static/js",
waitSeconds: 0 // Disable require.js load timeout
});
//
// LIBRARY REQUIREMENTS
//
// In the require function, we include the necessary libraries and modules for
// the HTML dashboard. Then, we pass variable names for these libraries and
// modules as function parameters, in order.
//
// When you add libraries or modules, remember to retain this mapping order
// between the library or module and its function parameter. You can do this by
// adding to the end of these lists, as shown in the commented examples below.
require([
"splunkjs/mvc",
"splunkjs/mvc/utils",
"splunkjs/mvc/tokenutils",
"underscore",
"jquery",
"splunkjs/mvc/simplexml",
"splunkjs/mvc/layoutview",
"splunkjs/mvc/simplexml/dashboardview",
"splunkjs/mvc/simplexml/dashboard/panelref",
"splunkjs/mvc/simplexml/element/chart",
"splunkjs/mvc/simplexml/element/event",
"splunkjs/mvc/simplexml/element/html",
"splunkjs/mvc/simplexml/element/list",
"splunkjs/mvc/simplexml/element/map",
"splunkjs/mvc/simplexml/element/single",
"splunkjs/mvc/simplexml/element/table",
"splunkjs/mvc/simplexml/element/visualization",
"splunkjs/mvc/simpleform/formutils",
"splunkjs/mvc/simplexml/eventhandler",
"splunkjs/mvc/simplexml/searcheventhandler",
"splunkjs/mvc/simpleform/input/dropdown",
"splunkjs/mvc/simpleform/input/radiogroup",
"splunkjs/mvc/simpleform/input/linklist",
"splunkjs/mvc/simpleform/input/multiselect",
"splunkjs/mvc/simpleform/input/checkboxgroup",
"splunkjs/mvc/simpleform/input/text",
"splunkjs/mvc/simpleform/input/timerange",
"splunkjs/mvc/simpleform/input/submit",
"splunkjs/mvc/searchmanager",
"splunkjs/mvc/savedsearchmanager",
"splunkjs/mvc/postprocessmanager",
"splunkjs/mvc/simplexml/urltokenmodel"
// Add comma-separated libraries and modules manually here, for example:
// ..."splunkjs/mvc/simplexml/urltokenmodel",
// "splunkjs/mvc/tokenforwarder"
],
function(
mvc,
utils,
TokenUtils,
_,
$,
DashboardController,
LayoutView,
Dashboard,
PanelRef,
ChartElement,
EventElement,
HtmlElement,
ListElement,
MapElement,
SingleElement,
TableElement,
VisualizationElement,
FormUtils,
EventHandler,
SearchEventHandler,
DropdownInput,
RadioGroupInput,
LinkListInput,
MultiSelectInput,
CheckboxGroupInput,
TextInput,
TimeRangeInput,
SubmitButton,
SearchManager,
SavedSearchManager,
PostProcessManager,
UrlTokenModel
// Add comma-separated parameter names here, for example:
// ...UrlTokenModel,
// TokenForwarder
) {
var pageLoading = true;
//
// TOKENS
//
// Create token namespaces
var urlTokenModel = new UrlTokenModel();
mvc.Components.registerInstance('url', urlTokenModel);
var defaultTokenModel = mvc.Components.get('default', {create: true});
var submittedTokenModel = mvc.Components.get('submitted', {create: true});
urlTokenModel.on('url:navigate', function() {
defaultTokenModel.set(urlTokenModel.toJSON());
if (!_.isEmpty(urlTokenModel.toJSON()) && !_.all(urlTokenModel.toJSON(), _.isUndefined)) {
submitTokens();
} else {
submittedTokenModel.clear();
}
});
// Initialize tokens
defaultTokenModel.set(urlTokenModel.toJSON());
function submitTokens() {
// Copy the contents of the defaultTokenModel to the submittedTokenModel and urlTokenModel
FormUtils.submitForm({ replaceState: pageLoading });
}
function setToken(name, value) {
defaultTokenModel.set(name, value);
submittedTokenModel.set(name, value);
}
function unsetToken(name) {
defaultTokenModel.unset(name);
submittedTokenModel.unset(name);
}
//
// SEARCH MANAGERS
//
var search1 = new SearchManager({
"id": "search1",
"search": "index=genericstats sourcetype=stats | stats latest(customername) as customername by customer",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search2 = new SearchManager({
"id": "search2",
"search": "index=genericstats sourcetype=stats customer=$customer$ | lookup alert_disable hostname | stats latest(hostname) as hostname latest(alert_enabled) as alert_enabled by id | where NOT alert_enabled = \"false\"",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true});
var search3 = new SearchManager({
"id": "search3",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table KeyID, hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
var search4 = new SearchManager({
"id": "search4",
"search": "index=genericstats sourcetype=stats | lookup alert_disable hostname | eval KeyID = _key | fields KeyID hostname alert_enabled id | stats latest(hostname) as Hostname latest(KeyID) as KeyID latest(alert_enabled) as alert_enabled by id | WHERE alert_enabled = \"false\" OR alert_enabled = \"true\" | table Hostname",
"latest_time": "now",
"status_buckets": 0,
"sample_ratio": null,
"cancelOnUnload": true,
"earliest_time": "-4h@m",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
//
// SPLUNK LAYOUT
//
$('header').remove();
new LayoutView({"hideChrome": false, "hideSplunkBar": false, "hideAppBar": false, "hideFooter": false})
.render()
.getContainerElement()
.appendChild($('.dashboard-body')[0]);
//
// DASHBOARD EDITOR
//
new Dashboard({
id: 'dashboard',
el: $('.dashboard-body'),
showTitle: true,
editable: true
}, {tokens: true}).render();
//
// VIEWS: VISUALIZATION ELEMENTS
//
var element1 = new TableElement({
"id": "element1",
"drilldown": "none",
"rowNumbers": "undefined",
"wrap": "undefined",
"managerid": "search4",
"el": $('#element1')
}, {tokens: true, tokenNamespace: "submitted"}).render();
//
// VIEWS: FORM INPUTS
//
var input1 = new DropdownInput({
"id": "input1",
"choices": [],
"labelField": "customername",
"valueField": "customer",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.customer$",
"managerid": "search1",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
var input2 = new DropdownInput({
"id": "input2",
"choices": [],
"labelField": "hostname",
"valueField": "hostname",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.id$",
"managerid": "search2",
"el": $('#input2')
}, {tokens: true}).render();
input2.on("change", function(newValue) {
FormUtils.handleValueChange(input2);
});
var mypresetsettings={
showPresets:false,
showPresetsRealTime:false,
showPresetsRealTimeOnly:false,
showPresetsRelative:false,
showPresetsAllTime:false,
showCustom:true, // <-- indicates whether or not to show other panels then the presets panel
showCustomRealTime:false,
showCustomRelative:false,
showCustomDate:false, // Only show CustomDate
showCustomDateTime:true,
showCustomDateTimeSince:false,
showCustomAdvanced:false,
enableCustomAdvancedRealTime:false
};
var input3 = new TimeRangeInput({
"id": "input3",
"default": {"latest_time": "-24h@h", "earliest_time": "now"},
"earliest_time": "$form.field3.earliest$",
"latest_time": "$form.field3.latest$",
"dialogOptions": mypresetsettings,
"el": $('#input3')
}, {tokens: true}).render();
input3.on("change", function(newValue) {
FormUtils.handleValueChange(input3);
});
var input7 = new DropdownInput({
"id": "input7",
"choices": [],
"labelField": "hostname",
"valueField": "KeyID",
"showClearButton": true,
"selectFirstChoice": false,
"value": "$form.KeyID$",
"managerid": "search3",
"el": $('#input7')
}, {tokens: true}).render();
input7.on("change", function(newValue) {
FormUtils.handleValueChange(input7);
});
//
// SERVICE OBJECT
//
// Create a service object using the Splunk SDK for JavaScript
// to send REST requests
var service = mvc.createService({ owner: "nobody" });
//
// DELETE BUTTON
//
// Call this function when the Delete Record button is clicked
$("#deleteRecord").click(function() {
// Get the value of the key ID field
var tokens = mvc.Components.get("default");
var form_keyid = tokens.get("KeyID");
// Delete the record that corresponds to the key ID using
// the del method to send a DELETE request
// to the storage/collections/data/{collection}/ endpoint
service.del("/servicesNS/nobody/<app>/storage/collections/data/alert_disable/" + encodeURIComponent(form_keyid))
.done(function() {
// Run the search again to update the table
search3.startSearch();
search4.startSearch();
});
return false;
});
//
// SUBMIT FORM DATA
//
//var submit = new SubmitButton({
// id: 'submit',
// el: $('#search_btn')
//}, {tokens: true}).render();
//submit.on("submit", function() {
$("#disableButton").click(function() {
submitTokens();
// When the Submit button is clicked, get all the form fields by accessing token values
var tokens = mvc.Components.get("default");
var form_hostname = tokens.get("id");
var form_timeframe_start = tokens.get("field3.earliest");
var form_timeframe_end = tokens.get("field3.latest");
var form_enabled = "false";
console.log(form_timeframe_start);
console.log(form_timeframe_end);
// Create a dictionary to store the field names and values
var record = {
"hostname": form_hostname,
"alert_enabled": form_enabled,
"start": form_timeframe_start,
"end": form_timeframe_end
};
// Use the request method to send a REST POST request
// to the storage/collections/data/{collection}/ endpoint
service.request(
"/servicesNS/nobody/<app>/storage/collections/data/alert_disable/",
"POST",
null,
null,
JSON.stringify(record),
{"Content-Type": "application/json"},
null)
.done(function() {
// Run the search again to update the table
search2.startSearch();
search3.startSearch();
search4.startSearch();
// Clear the form fields
// $("#formAlertsEnabled input[type=text]").val("");
});
});
// Initialize time tokens to default
if (!defaultTokenModel.has('earliest') && !defaultTokenModel.has('latest')) {
defaultTokenModel.set({ earliest: '0', latest: '' });
}
if (!_.isEmpty(urlTokenModel.toJSON())){
submitTokens();
}
//
// DASHBOARD READY
//
DashboardController.ready();
pageLoading = false;
}
);
// ]]>
</script>
</body>
</html>
Hey. I believe those two token can be retrieved by the token of the time picker concatenated with for earliest/latest.
var form_earliest = tokens.get("input3.earliest");
var form_latest = tokens.get("input3.latest");
Yes, that would make sense, however that dosnt work 😞
You were absolute right in your first answer, but the issue were in my properties for inputs3.
I have awarded you the points.
Ok good to know you figured it out. Please upvote the comment/answer useful for the final resolution of this. Thanks
Recall that you should get those from the submitted tokens, like the example I;m showing below for a TimePicker with token "time"
I assure that this example is getting the tokens out was expected:
require([
"splunkjs/mvc",
"splunkjs/mvc/searchmanager",
"splunkjs/mvc/postprocessmanager",
"splunkjs/mvc/eventsviewerview",
"splunkjs/mvc/chartview",
"splunkjs/mvc/tableview",
"splunkjs/mvc/splunkmapview",
"splunkjs/mvc/tokenutils",
"splunkjs/mvc/simplexml/ready!",
"splunkjs/mvc/radiogroupview",
"splunkjs/mvc/dropdownview"
], function(
mvc,
SearchManager,
PostProcessManager,
EventsViewer,
ChartView,
TableView,
SplunkMapView,
TokenUtils,
RadioGroupView,
DropdownView
) {
//Loading all tokens
// GET TOKENS FROM SUBMITTED; SET TOKEN IN DEFAULT AND SUBMITTED
var tokens_default = mvc.Components.get("default");
var submittedTokenModel = mvc.Components.get("submitted");
// TABLE OF SYSTEMS
var earl=submittedTokenModel.get("time.earliest");
var late=submittedTokenModel.get("time.latest");
console.log(earl);
console.log(late);
});
Are you sure you don't have other mistakes earlier? Because the tokens get is working as usual...
Dosnt work either. Actually i get
VM2351 alert_disabling:489 Uncaught TypeError: Cannot read property 'get' of undefined
at HTMLButtonElement.<anonymous> (VM2351 alert_disabling:489)
at HTMLButtonElement.dispatch (VM2340 index.js:26)
at HTMLButtonElement.elemData.handle (VM2340 index.js:26)
(anonymous) @ VM2351 alert_disabling:489
dispatch @ VM2340 index.js:26
elemData.handle @ VM2340 index.js:26
With above.
And no, im not sure i have any mistakes ealier, thats why im asking for assistance 😉
My example above involved having the time picker defined in SimpleXML and worked fine.
Having just the time picker in simpleXML is not an option for you?
That would be a great way to solve this, however im in splunkcloud and not able to add a js file 😞
Thats why i try to fix this with an html dashboard instead.