Dashboards & Visualizations

Failed to execute button | ModalView | javascript | Why is popup.js file unable to see selected_values_array variable?

crteixeira
Explorer

Hey guys, good night, how are you?

I have a big problem

I created an app with the integration of a checkbox with ModalView

I need to send the data shown in the modal to a lookup, but the popup.js file is unable to see the selected_values_array variable from the checkbox.js file

Have you ever been through this? Can you help me?

Thanks

 

checkbox.js

 

 

 

require([
    'underscore',
    'jquery',
    'backbone',
    '../app/meuapp/popup',
    'splunkjs/mvc',
    'splunkjs/mvc/tableview',
    'splunkjs/mvc/searchmanager',
    'splunkjs/mvc/simplexml/ready!'
], function (_, $, Backbone, ModalView, mvc, TableView, SearchManager) {
    // Access the "default" token model
    var tokens = mvc.Components.get("default");
    var selected_values_array = [];
    var submittedTokens = mvc.Components.get('submitted');


    var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
        canRender: function (cell) {
            return _(['teste']).contains(cell.field);
        },
        render: function ($td, cell) {
            var a = $('<div>').attr({ "id": "chk-URL" + cell.value, "value": cell.value }).addClass('checkbox').click(function () {
                // console.log("checked",$(this).attr('class'));
                // console.log("checked",$(this).attr('value'));
                if ($(this).attr('class') === "checkbox") {
                    selected_values_array.push($(this).attr('value'));
                    $(this).removeClass();
                    $(this).addClass("checkbox checked");
                }
                else {
                    $(this).removeClass();
                    $(this).addClass("checkbox");
                    var i = selected_values_array.indexOf($(this).attr('value'));
                    if (i != -1) {
                        selected_values_array.splice(i, 1);
                    }
                    // Change the value of a token $mytoken$
                }
                console.log(selected_values_array);
            }).appendTo($td);
            console.log(selected_values_array);
        }
    });

    var detailSearch = new SearchManager({
        id: "detailSearch",
        earliest_time: "$time$",
        latest_time: "$time$",
        preview: true,
        cache: false,
        search: "| makeresults | eval myvalue=\"$mytoken$\" | makemv delim=\",\" myvalue | stats count by myvalue | table myvalue"
    }, { tokens: true, tokenNamespace: "submitted" });
 
    //List of table IDs
    var tableIDs = ["myTable"];
    for (i = 0; i < tableIDs.length; i++) {
        var sh = mvc.Components.get(tableIDs[i]);
        if (typeof (sh) != "undefined") {
            sh.getVisualization(function (tableView) {
                // Add custom cell renderer and force re-render
                tableView.table.addCellRenderer(new CustomRangeRenderer());
                tableView.table.render();
            });
        }
    };

    $(document).ready(function () {
        $("#mybutton").on("click", function (e) {
            e.preventDefault();
            tokens.set("mytoken", selected_values_array.join());
            submittedTokens.set(tokens.toJSON());
            var modal = new ModalView({ title: "ModalView Window", search: detailSearch });
            modal.show();
            console.log(tokens);
            console.log(selected_values_array  + " selected_values_array");
            console.log(modal  + " modal");
            //console.log(render);
        });
    });
});

 

 

 

 

 

 

popup.js

 

 

 

define([
    'underscore',
    'backbone',
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/searchmanager',
    'splunkjs/mvc/simplexml/element/table',
    ], function(_, Backbone, $, mvc, SearchManager, TableElement) {

        var modalTemplate = "<div id=\"pivotModal\" class=\"modal\">" +
                       "<div class=\"modal-header\"><h3><%- title %></h3><button class=\"close\">Close</button></div>" +
                       "<div class=\"modal-body\"></div>" +
                       "<div class=\"modal-footer\"><button type=\"button\" id=\"teste\" class=\"confirm\">Confirmar</button></div>" +
                       "</div>" +
                       "<div class=\"modal-backdrop\"></div>";

        var ModalView = Backbone.View.extend({

            defaults: {
                   title: 'Not set'
            },

            initialize: function(options) {
                this.options = options;
                this.options = _.extend({}, this.defaults, this.options);
                this.childViews = [];
                console.log('Hello from the modal window: ', this.options.title);
                this.template = _.template(modalTemplate);
            },

            events: {
                   'click .close': 'close',
               'click .modal-backdrop': 'close',
               'click .confirm': 'confirm',
            },

            render: function() {
                var data = { title : this.options.title };
                    this.$el.html(this.template(data));
                return this;
            },

            show: function() {
                    $(document.body).append(this.render().el);

                $(this.el).find('.modal-body').append('<div id="modalVizualization"/>');

                $(this.el).find('.modal').css({
                    width:'90%',
                    height:'auto',
                    left: '5%',
                    'margin-left': '0',
                    'max-height':'100%'
                });

                var search = mvc.Components.get(this.options.search.id);

                var detailTable = new TableElement({
                        id: "detailTable",
                        managerid: search.name,
                        pageSize: "5",
                        el: $('#modalVizualization')
                }).render();

                this.childViews.push(detailTable);
                search.startSearch();
            },

            close: function() {
                   this.unbind();
               this.remove();
               _.each(this.childViews, function(childView) {

                   childView.unbind();
                   childView.remove();

               });
            },

            confirm: function(selected_values_array) {
                tokens.set("mytoken", selected_values_array.join());
                submittedTokens.set(tokens.toJSON());
                new SearchManager({
                    id: "envSearch",
                    earliest_time: "$time$",
                    latest_time: "$time$",
                    preview: true,
                    cache: false,
                    search: "| makeresults | eval myvalue=\"$mytoken$\" | makemv delim=\",\" myvalue | rename myvalue as URL | stats count by URL | table URL | outputlookup append=t dev-tk"
                });
            }
        });

        return ModalView;
    });

 

 

 

 

chexkbox.css

 

 

 

/* The standalone checkbox square*/
.checkbox {
  width:20px;
  height:20px;
  border: 1px solid #000;
  display: inline-block;
}

/* This is what simulates a checkmark icon */
.checkbox.checked:after {
  content: '';
  display: block;
  width: 4px;
  height: 7px;

  /* "Center" the checkmark */
  position:relative;
  top:4px;
  left:7px;

  border: solid #000;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);

 

 

 

 

dash.xml

 

 

 

<dashboard script="checkbox.js" stylesheet="checkbox.css">
<label>Teste </label>
<row>
<panel>
<table id="myTable">
<title>My Table</title>
<search>
<query>index=_internal | stats count by sourcetype | eval teste=sourcetype</query>
<earliest>-15m</earliest>
<latest>now</latest>
</search>
<option name="count">10</option>
<option name="drilldown">row</option>
<option name="refresh.display">progressbar</option>
<drilldown>
<condition field="*"></condition>
</drilldown>
</table>
</panel>
</row>
<row>
<panel>
<html>
<div>
<input type="button" id="mybutton" value="My Button"/>
</div>
</html>
</panel>
</row>

</dashboard>

 

 

 

 

 

crteixeira_0-1660707041958.png

 

Labels (1)
0 Karma
1 Solution

kamlesh_vaghela
SplunkTrust
SplunkTrust

@crteixeira 

I have made some changes to your JS. Please try it and let me know if any issues.

popup.js

define([
  'underscore',
  'backbone',
  'jquery',
  'splunkjs/mvc',
  'splunkjs/mvc/searchmanager',
  'splunkjs/mvc/simplexml/element/table',
  ], function(_, Backbone, $, mvc, SearchManager, TableElement) {

      var modalTemplate = "<div id=\"pivotModal\" class=\"modal\">" +
                     "<div class=\"modal-header\"><h3><%- title %></h3><button class=\"close\">Close</button></div>" +
                     "<div class=\"modal-body\"></div>" +
                     "<div class=\"modal-footer\"><button type=\"button\" id=\"teste\" class=\"confirm\">Confirmar</button></div>" +
                     "</div>" +
                     "<div class=\"modal-backdrop\"></div>";

      var ModalView = Backbone.View.extend({

          defaults: {
                 title: 'Not set'
          },

          initialize: function(options) {
              this.options = options;
              this.options = _.extend({}, this.defaults, this.options);
              this.childViews = [];
              console.log('Hello from the modal window: ', this.options.title);
              this.template = _.template(modalTemplate);
          },

          events: {
                 'click .close': 'close',
             'click .modal-backdrop': 'close',
             'click .confirm': 'confirm',
          },

          render: function() {
              var data = { title : this.options.title };
                  this.$el.html(this.template(data));
              return this;
          },

          show: function() {
                  $(document.body).append(this.render().el);

              $(this.el).find('.modal-body').append('<div id="modalVizualization"/>');

              $(this.el).find('.modal').css({
                  width:'90%',
                  height:'auto',
                  left: '5%',
                  'margin-left': '0',
                  'max-height':'100%'
              });

              var search = mvc.Components.get(this.options.search.id);

              var detailTable = new TableElement({
                      id: "detailTable",
                      managerid: search.name,
                      pageSize: "5",
                      el: $('#modalVizualization')
              }).render();

              this.childViews.push(detailTable);
              search.startSearch();
          },

          close: function() {
                 this.unbind();
             this.remove();
             _.each(this.childViews, function(childView) {

                 childView.unbind();
                 childView.remove();

             });
          },

          confirm: function() {
                console.log(this.options.selected_values_array);
              // tokens.seCredit t("mytoken", selected_values_array.join());
              // submittedTokens.set(tokens.toJSON());
              new SearchManager({
                  id: "envSearch",
                  // earliest_time: "$time$",
                  // latest_time: "$time$",
                  preview: true,
                  cache: false,
                  search: "| makeresults | eval myvalue=\""+this.options.selected_values_array+"\" | makemv delim=\",\" myvalue | rename myvalue as URL | stats count by URL | table URL | outputlookup append=t dev-tk"
              });
          }
      });

      return ModalView;
  });

 

checkbox.js

require([
  'underscore',
  'jquery',
  'backbone',
  '../app/search/crteixeira_popup',
  'splunkjs/mvc',
  'splunkjs/mvc/tableview',
  'splunkjs/mvc/searchmanager',
  'splunkjs/mvc/simplexml/ready!'
], function (_, $, Backbone, ModalView, mvc, TableView, SearchManager) {
  // Access the "default" token model
  var tokens = mvc.Components.get("default");
  var selected_values_array = [];
  var submittedTokens = mvc.Components.get('submitted');


  var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
      canRender: function (cell) {
          return _(['teste']).contains(cell.field);
      },
      render: function ($td, cell) {
          var a = $('<div>').attr({ "id": "chk-URL" + cell.value, "value": cell.value }).addClass('checkbox').click(function () {
              // console.log("checked",$(this).attr('class'));
              // console.log("checked",$(this).attr('value'));
              if ($(this).attr('class') === "checkbox") {
                  selected_values_array.push($(this).attr('value'));
                  $(this).removeClass();
                  $(this).addClass("checkbox checked");
              }
              else {
                  $(this).removeClass();
                  $(this).addClass("checkbox");
                  var i = selected_values_array.indexOf($(this).attr('value'));
                  if (i != -1) {
                      selected_values_array.splice(i, 1);
                  }
                  // Change the value of a token $mytoken$
              }
              console.log(selected_values_array);
          }).appendTo($td);
          console.log(selected_values_array);
      }
  });

  var detailSearch = new SearchManager({
      id: "detailSearch",
      earliest_time: "$time$",
      latest_time: "$time$",
      preview: true,
      cache: false,
      search: "| makeresults | eval myvalue=\"$mytoken$\" | makemv delim=\",\" myvalue | stats count by myvalue | table myvalue"
  }, { tokens: true, tokenNamespace: "submitted" });

  //List of table IDs
  var tableIDs = ["myTable"];
  for (i = 0; i < tableIDs.length; i++) {
      var sh = mvc.Components.get(tableIDs[i]);
      if (typeof (sh) != "undefined") {
          sh.getVisualization(function (tableView) {
              // Add custom cell renderer and force re-render
              tableView.table.addCellRenderer(new CustomRangeRenderer());
              tableView.table.render();
          });
      }
  };

  $(document).ready(function () {
      $("#mybutton").on("click", function (e) {
          e.preventDefault();
          tokens.set("mytoken", selected_values_array.join());
          submittedTokens.set(tokens.toJSON());
          var modal = new ModalView({ title: "ModalView Window", search: detailSearch, selected_values_array:selected_values_array });
          modal.show();
          console.log(tokens);
          console.log(selected_values_array  + " selected_values_array");
          console.log(modal  + " modal");
          //console.log(render);
      });
  });
});

 

I hope this will help you.

Thanks
KV


If any of my replies help you to solve the problem Or gain knowledge, an upvote would be appreciated.

 

View solution in original post

0 Karma

crteixeira
Explorer

Perfect @kamlesh_vaghela !!!


Thank you!!
I'm very happy, it worked perfectly

And even with your code I learned to import the variable, thank you very much

Now I'm going to proceed with the customizations, thank you

0 Karma

kamlesh_vaghela
SplunkTrust
SplunkTrust

Glad to help you @crteixeira 🙂 

 

Thanks
KV
If any of my replies help you to solve the problem Or gain knowledge, an upvote would be appreciated.

 

0 Karma

kamlesh_vaghela
SplunkTrust
SplunkTrust

@crteixeira 

Your code looks good to me. Just one question. In the popup modal, there is a confirm button. What is the logic behind it?

I found some code mistakes where a few tokens are undefined. Like, `tokens` , `submittedTokens`, `time` .  Please elaborate the requirement so I can help you in this code as well.

 

confirm: function(selected_values_array) {
                tokens.set("mytoken", selected_values_array.join());
                submittedTokens.set(tokens.toJSON());
                new SearchManager({
                    id: "envSearch",
                    earliest_time: "$time$",
                    latest_time: "$time$",
                    preview: true,
                    cache: false,
                    search: "| makeresults | eval myvalue=\"$mytoken$\" | makemv delim=\",\" myvalue | rename myvalue as URL | stats count by URL | table URL | outputlookup append=t dev-tk"
                });
            }

 

I hope this will help you.

Thanks
KV


If any of my reply helps you to solve the problem Or gain knowledge, an upvote would be appreciated.

0 Karma

crteixeira
Explorer

The logic would be that the URLs marked on the panel appear in the popup if they were a preview

And when you click confirm you will be sent to a kvstore

The problem is that the popup.js file does not recognize the Token being worked on in the checkbox.js file so it does not accept the "join"

I understand that "mytoken" data is stored in "selected_values_array" so I tried calling it but it doesn't work

0 Karma

kamlesh_vaghela
SplunkTrust
SplunkTrust

@crteixeira 

I have made some changes to your JS. Please try it and let me know if any issues.

popup.js

define([
  'underscore',
  'backbone',
  'jquery',
  'splunkjs/mvc',
  'splunkjs/mvc/searchmanager',
  'splunkjs/mvc/simplexml/element/table',
  ], function(_, Backbone, $, mvc, SearchManager, TableElement) {

      var modalTemplate = "<div id=\"pivotModal\" class=\"modal\">" +
                     "<div class=\"modal-header\"><h3><%- title %></h3><button class=\"close\">Close</button></div>" +
                     "<div class=\"modal-body\"></div>" +
                     "<div class=\"modal-footer\"><button type=\"button\" id=\"teste\" class=\"confirm\">Confirmar</button></div>" +
                     "</div>" +
                     "<div class=\"modal-backdrop\"></div>";

      var ModalView = Backbone.View.extend({

          defaults: {
                 title: 'Not set'
          },

          initialize: function(options) {
              this.options = options;
              this.options = _.extend({}, this.defaults, this.options);
              this.childViews = [];
              console.log('Hello from the modal window: ', this.options.title);
              this.template = _.template(modalTemplate);
          },

          events: {
                 'click .close': 'close',
             'click .modal-backdrop': 'close',
             'click .confirm': 'confirm',
          },

          render: function() {
              var data = { title : this.options.title };
                  this.$el.html(this.template(data));
              return this;
          },

          show: function() {
                  $(document.body).append(this.render().el);

              $(this.el).find('.modal-body').append('<div id="modalVizualization"/>');

              $(this.el).find('.modal').css({
                  width:'90%',
                  height:'auto',
                  left: '5%',
                  'margin-left': '0',
                  'max-height':'100%'
              });

              var search = mvc.Components.get(this.options.search.id);

              var detailTable = new TableElement({
                      id: "detailTable",
                      managerid: search.name,
                      pageSize: "5",
                      el: $('#modalVizualization')
              }).render();

              this.childViews.push(detailTable);
              search.startSearch();
          },

          close: function() {
                 this.unbind();
             this.remove();
             _.each(this.childViews, function(childView) {

                 childView.unbind();
                 childView.remove();

             });
          },

          confirm: function() {
                console.log(this.options.selected_values_array);
              // tokens.seCredit t("mytoken", selected_values_array.join());
              // submittedTokens.set(tokens.toJSON());
              new SearchManager({
                  id: "envSearch",
                  // earliest_time: "$time$",
                  // latest_time: "$time$",
                  preview: true,
                  cache: false,
                  search: "| makeresults | eval myvalue=\""+this.options.selected_values_array+"\" | makemv delim=\",\" myvalue | rename myvalue as URL | stats count by URL | table URL | outputlookup append=t dev-tk"
              });
          }
      });

      return ModalView;
  });

 

checkbox.js

require([
  'underscore',
  'jquery',
  'backbone',
  '../app/search/crteixeira_popup',
  'splunkjs/mvc',
  'splunkjs/mvc/tableview',
  'splunkjs/mvc/searchmanager',
  'splunkjs/mvc/simplexml/ready!'
], function (_, $, Backbone, ModalView, mvc, TableView, SearchManager) {
  // Access the "default" token model
  var tokens = mvc.Components.get("default");
  var selected_values_array = [];
  var submittedTokens = mvc.Components.get('submitted');


  var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
      canRender: function (cell) {
          return _(['teste']).contains(cell.field);
      },
      render: function ($td, cell) {
          var a = $('<div>').attr({ "id": "chk-URL" + cell.value, "value": cell.value }).addClass('checkbox').click(function () {
              // console.log("checked",$(this).attr('class'));
              // console.log("checked",$(this).attr('value'));
              if ($(this).attr('class') === "checkbox") {
                  selected_values_array.push($(this).attr('value'));
                  $(this).removeClass();
                  $(this).addClass("checkbox checked");
              }
              else {
                  $(this).removeClass();
                  $(this).addClass("checkbox");
                  var i = selected_values_array.indexOf($(this).attr('value'));
                  if (i != -1) {
                      selected_values_array.splice(i, 1);
                  }
                  // Change the value of a token $mytoken$
              }
              console.log(selected_values_array);
          }).appendTo($td);
          console.log(selected_values_array);
      }
  });

  var detailSearch = new SearchManager({
      id: "detailSearch",
      earliest_time: "$time$",
      latest_time: "$time$",
      preview: true,
      cache: false,
      search: "| makeresults | eval myvalue=\"$mytoken$\" | makemv delim=\",\" myvalue | stats count by myvalue | table myvalue"
  }, { tokens: true, tokenNamespace: "submitted" });

  //List of table IDs
  var tableIDs = ["myTable"];
  for (i = 0; i < tableIDs.length; i++) {
      var sh = mvc.Components.get(tableIDs[i]);
      if (typeof (sh) != "undefined") {
          sh.getVisualization(function (tableView) {
              // Add custom cell renderer and force re-render
              tableView.table.addCellRenderer(new CustomRangeRenderer());
              tableView.table.render();
          });
      }
  };

  $(document).ready(function () {
      $("#mybutton").on("click", function (e) {
          e.preventDefault();
          tokens.set("mytoken", selected_values_array.join());
          submittedTokens.set(tokens.toJSON());
          var modal = new ModalView({ title: "ModalView Window", search: detailSearch, selected_values_array:selected_values_array });
          modal.show();
          console.log(tokens);
          console.log(selected_values_array  + " selected_values_array");
          console.log(modal  + " modal");
          //console.log(render);
      });
  });
});

 

I hope this will help you.

Thanks
KV


If any of my replies help you to solve the problem Or gain knowledge, an upvote would be appreciated.

 

0 Karma
Get Updates on the Splunk Community!

What's new in Splunk Cloud Platform 9.1.2312?

Hi Splunky people! We are excited to share the newest updates in Splunk Cloud Platform 9.1.2312! Analysts can ...

What’s New in Splunk Security Essentials 3.8.0?

Splunk Security Essentials (SSE) is an app that can amplify the power of your existing Splunk Cloud Platform, ...

Let’s Get You Certified – Vegas-Style at .conf24

Are you ready to level up your Splunk game? Then, let’s get you certified live at .conf24 – our annual user ...