Dashboards & Visualizations

How to add css class to table field by input in Splunk javascript for dashboard customer render?

willtseng0217
New Member

Dear all Splunkers!!

Please help, I am trying to use Javascript to add CSS class in search result table by input.
As in pic 1, it already adds some class at result just like my input.
The blue underline is called CSS, red frame is a keyword that needs to be highlighted. alt text

But, it doesn't change any font color and this is my XML code.

<form script="highlight.js" stylesheet="highlight.css">
  <label>[Syslog Query ]</label>
  <fieldset submitButton="false">
    <input type="text" token="Token_1" searchWhenChanged="true">
      <label>Token_1</label>
      <default>*</default>
     </input>

    <input type="time" token="Time_Input_Token" searchWhenChanged="true">
      <label></label>
      <default>
        <earliest>-30d@d</earliest>
        <latest>now</latest>
      </default>
    </input>

  </fieldset>
  <search id="Syslog_Master_Search">
    <query>
      <![CDATA[   ]]>
    </query>
    <earliest>$Time_Input_Token.earliest$</earliest>
    <latest>$Time_Input_Token.latest$</latest>
  </search>

  <row>
    <panel>
      <title>[test]</title>

      <input type="text" token="Token_2" searchWhenChanged="true">
        <label>Token2</label>
        <default>*</default>
      </input>
         <table id="Syslog_Table">
        <search>
          <query>
            index=udp514idx *$Token_1$*
            | table Time "Host Name" IP SysLog  
            | eval Search_Keyword = "(" . mvjoin(trim(split(replace(replace("$Token_2$", "\.", "\."), "\*", ".*"), ",")), "|") . ")"
            | where match(SysLog, "(?i)" . Search_Keyword)  
            | eval SysLog = if("$Token_2$" == "*", SysLog, replace(SysLog, "(?i)(" . Search_Keyword .")", "&lt;b class=\"Uncategorized_Syslog_Keyword_Highlight\"&gt;\1&lt;/b&gt;"))
            | table Time "Host Name" IP SysLog

          </query>

        </search>
        <option name="wrap">false</option>
        <option name="rowNumbers">true</option>
        <option name="dataOverlayMode">none</option>
        <option name="drilldown">none</option>
        <option name="count">20</option>
        <fields>["Time","Host Name","IP","SysLog"]</fields>
      </table>
    </panel>
  </row>

</form>

and this is my javascript

// Translations for zh_TW
i18n_register({"catalog": {}, "plural": function(n) { return n != 1; }});


require([
    'underscore',
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/tableview',
    'splunkjs/mvc/simplexml/ready!'
], function(_, $, mvc, TableView) {

     // Row Coloring Example with custom, client-side range interpretation

    var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            // Enable this custom cell renderer for both the active_hist_searches and the active_realtime_searches field
            return _(['SysLog']).contains(cell.field);
        },
        render: function($td, cell) {

            $td.addClass(cell.field);

            // Update the cell content
            $td.html(cell.value).addClass('string');
        }
    });

    mvc.Components.get('Syslog_Table').getVisualization(function(tableView) {
        tableView.addCellRenderer(new CustomRangeRenderer());
    });  

});

The result I expected is as below, my input keyword is highlighted in red.

Thank u so much!!

alt text

0 Karma

niketnilay
Legend

@willtseng0217 Please find below a run anywhere dashboard example with table having id="table1" and a column called message on which filter is applied through search token tokFilter. Simple XML JavaScript extension along with SplunkJS Stack has been used for the same.

Following is the piece of JavaScript Extension code which applied regular expression based filter on table text and replaces with rich content with html/style ( i.e. bold font and red color). Finally, updated text is applied to table cell using .html() function.

     render: function($td, cell) {
         var strText=cell.value;
         var regEx = new RegExp(strFilterText, "gi");
         //Apply regular expression to replace Filter Text with html content bold font and red color
         strText=strText.replace(regEx, '<b style="color:red;">$&</b>');
         // Add html content to table cell of string class
         $td.addClass('string').html(_.template(strText));
     } 

PS: JavaScript would need to change as per how you are handling the input token and also if you want any special highlight functionality. Current Regular Expression filter applied in JavaScript is case insensitive i.e. gi

alt text
Following is the Run anywhere Simple XML Dashboard Code:

<form script="highlight_selected_text_in_table.js">
  <label>Highlight Selected Text In Table</label>
  <fieldset submitButton="false">
    <input type="time" token="tokTime" searchWhenChanged="true">
      <label></label>
      <default>
        <earliest>-24h@h</earliest>
        <latest>now</latest>
      </default>
    </input>
    <input type="text" token="tokText" searchWhenChanged="true">
      <label>Apply Text Filter</label>
      <default></default>
      <change>
        <condition match="$value$==&quot;\*&quot;">
          <unset token="tokFilter"></unset>
        </condition>
        <condition>
          <set token="tokFilter">$value$</set>
        </condition>
      </change>
    </input>
  </fieldset>
  <row>
    <panel>
      <table id="table1">
        <search>
          <query>| makeresults
| fields - _time
| eval message="my test data one; my sample data for testing;"
| makemv message delim=";"
| mvexpand message
| search message="*$tokText$*"</query>
          <earliest>$tokTime.earliest$</earliest>
          <latest>$tokTime.latest$</latest>
        </search>
        <option name="count">10</option>
        <option name="refresh.display">progressbar</option>
      </table>
    </panel>
  </row>
</form>

Following is the JavaScript code highlight_selected_text_in_table.js:

require([
    "underscore",
    "jquery",
    "splunkjs/mvc",
    "splunkjs/mvc/tableview",
    "splunkjs/mvc/simplexml/ready!"
], function(_, $, mvc, TableView) {

    var defaultTokenModel=mvc.Components.get("default");
    //tableView with id="table1" in SimpleXML
    var tableView=mvc.Components.get("table1");
    var strFilterText="";

    var CustomIconRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            //Applied to message column in the Table 
            return cell.field === "message";
        },
        render: function($td, cell) {
            var strText=cell.value;
            var regEx = new RegExp(strFilterText, "gi");
            //Apply regular expression to replace Filter Text with html content bold font and red color
            strText=strText.replace(regEx, '<b style="color:red;">$&</b>');
            // Add html content to table cell of string class
            $td.addClass('string').html(_.template(strText));
        }
    });

    // When Text box input value changes handle tokFilter 
    defaultTokenModel.on("change:tokFilter",function(newtokFilter,tokFilter,options){
        // Only if tokFilter has value apply Custom Table Render
        // Since token tokFilter is used in table query Table is supposed to render again 
        if(tokFilter!==undefined || tokFilter!=="$value$"){
            strFilterText=tokFilter;
            tableView.getVisualization(function(tableView){
                // Register custom cell renderer, the table will re-render automatically
                tableView.addCellRenderer(new CustomIconRenderer());
            });         
        }
    });
});

PS: As you might already know the JavaScript file would need to be placed under $SPLUNK_HOME/etc/apps/<yourAppName>/appserver/static folder. And this change would require restart, refresh, bump of your Splunk instance and also might require clearing of internet browser history.

Please try out and confirm.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma
Register for .conf21 Now! Go Vegas or Go Virtual!

How will you .conf21? You decide! Go in-person in Las Vegas, 10/18-10/21, or go online with .conf21 Virtual, 10/19-10/20.