All Apps and Add-ons

Color individual table cell based on value

sc0tt
Builder

I know that I can color an entire row using the table rowClass param in Sideview like so

<param name="rowClass">$row.fields.range$</param>

and then creating custom css

.Table tr.high td {
background-color:#e67918;
color:#fff;
}

but is there a way to color an individual cell based on a value?

Edit: To expand this question based on the below answers by gpradeepkumarreddy

I think I am missing something. Based on the suggestions below I have the following javascript in /apps/MyApp/appserver/static/application.js but I do not see any classes added to the table.

if ((Splunk.util.getCurrentView() == "live_dashboard") && Splunk.Module.SimpleResultsTable) {
Splunk.Module.SimpleResultsTable = $.klass(Splunk.Module.SimpleResultsTable, {
    onResultsRendered: function($super) {
        var retVal = $super();

this.myCustomHeatMapDecorator();
        return retVal;
    },

myCustomHeatMapDecorator: function () {

//Your code goes here
var sessions = (tds[1].innerText) ? tds[1].innerText : tds[1].textContent;
    if(sessions>1000){ //threshold to color
        {
        tr.find("td:nth-child(2)").addClass("colorRed"); //colorRed is a custom css class for a table cell
        }
    }
//end

}

dteo827
Explorer

For those of of you out there who want to have row highlighting by time, and not some obscure number, here is my modification:

Quick overview:

  • Results occurring less than ten minutes ago It highlights one color (specified by range-severe - usually light red)
  • Results occurring less than an hour ago It highlights another color (specified by range-severe - usually light orange)
  • All other results highlight to another color (specified by range-normal- I set it to grey (F5F5F5))

In order for [grey] highlighting to work, you have to add this to your table_decorations.css

#highlight tr.range-normal td {
    background-color: #F5F5F5 !important;
}

Please forgive my childish use of substring() - I spent a couple hours on Code academy to learn the basics of Javascript before writing this.
Otherwise, here is the functioning, albeit messy script:

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 _(['_time']).contains(cell.field);
        },
        render: function($td, cell) {
            // Add a class to the cell based on the returned value
            //Parse cell object for each key
            for (var key in cell) {
                this[key] = cell[key];
            }
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear();

            if(dd<10) {
                dd='0'+dd
            }

            if(mm<10) {
                mm='0'+mm
            }
            //Takes javascripts' time and converts it to Splunk format 
            today = yyyy+'-'+mm+'-'+dd;

            //subtracts ten minutes or an hour from the current time
            var today_time_minus_hour = new Date; today_time_minus_hour.setHours( today_time_minus_hour.getHours() - 1 );
            var today_time_minus_hour_sub = (String(today_time_minus_hour)).substring(16,24);
            var today_time_minus_ten_mins = new Date; today_time_minus_ten_mins.setMinutes( today_time_minus_ten_mins.getMinutes() - 10 );
            var today_time_minus_ten_mins_sub = (String(today_time_minus_ten_mins)).substring(16,24);

            //Compare's the time of the log to the current time (Minus either ten minutes or an Hour) and sets the highlighting
            if (cell.field === '_time') {
                if ((String(cell.value)).substring(0,10) == today) {
                    if (cell.value.substring(11,19) > today_time_minus_ten_mins_sub) {
                        $td.addClass('range-cell').addClass('range-severe');
                    } else if (cell.value.substring(11,19) > today_time_minus_hour_sub) {
                        $td.addClass('range-cell').addClass('range-elevated');
                    }
                } else {
                    if (cell.value.substring(11,19) < today_time_minus_hour_sub) {
                        $td.addClass('range-cell').addClass('range-normal');
                    }
                }
            }
            // Update the cell content
            update_date = ((cell.value.substring(0,10)) + " " + (cell.value).substring(11,19));
            $td.text(update_date);
        }
    });
    mvc.Components.get('highlight').getVisualization(function(tableView) {
        tableView.on('rendered', function() {
            // Apply class of the cells to the parent row in order to color the whole row
            tableView.$el.find('td.range-cell').each(function() {
                $(this).parents('tr').addClass(this.className);
            });
        });
        // Add custom cell renderer, the table will re-render automatically.
        tableView.addCellRenderer(new CustomRangeRenderer());
    });
});
0 Karma

LukeMurphey
Champion

Sure, check out this answer: http://answers.splunk.com/answers/83206/color-in-a-table-based-on-values.

Its pretty easy, just drop a bit of Javascript, then do your rendering via stylesheets.

sc0tt
Builder

Thanks! I wasn't putting the if statement in the correct place. I think this will work until the new version Sideview is released.

0 Karma

nlapier2
Path Finder

@sc0tt
If you have a column named "Value" and you want to color a cell red if over 100 ("Danger"), your $.each section of LukeMurphey's .js would look like this:

$.each( $('.SimpleResultsTable td'), function(index, value) {
if(parseInt($(this).text()) > 100)
{
$(this).attr('data-value', "Danger: Value" );
}
}

And then CSS could use this text to color the cell appropriately:

.SimpleResultsTable table.simpleResultsTable tr td[field="Value"][data-value="Danger: Value"] {
background-color: #C42323;
color: #CCCCCC;
font-weight: bold;
}

Repeat for any number of columns.

sc0tt
Builder

@nlapier2 Thanks for the tip. Can you provide an example of your modified solution?

0 Karma

nlapier2
Path Finder

@sc0tt I can't speak for the unreleased SideView solution, but if you're interested in doing numerical comparisons for LukeMurphy's solution, I found that it's not quite as easy as data-value>"100". What I ultimately ended up doing was checking in the JavaScript and then passing in a different result message to CSS depending on what the numerical comparison resulted in. I.e. in js I would check if $(this).text()>100 and then if it is I would pass something like "over100" or whatever to CSS, where it would highlight appropriately. Hope this helps.

0 Karma

nlapier2
Path Finder

@sc0tt Thanks! That helped a lot.

0 Karma

sc0tt
Builder

@nlapier2 I am using Version 6 as well. I had to modify the CSS to get it to work.

.SimpleResultsTable table.simpleResultsTable tr td[field="range"][data-value="high"] {
background-color: #C42323;
color: #CCCCCC;
font-weight: bold;
}

@nick is it possible to do this based on numerical comparisons as well (ie data-value>"100")?

nlapier2
Path Finder

Thanks, really appreciate it.

0 Karma

nick
Explorer

Yes, the custom JS solution here is tailored just for the SimpleResultsTable module. Sit tight and I will write back soon with an official answer to do this with Table and a customBehavior thereupon. Actually there is a whole feature to do this in Table coming, with no custom code, but that won't release until at least Sideview Utils 3.0 so pretend I didn't say anything.

0 Karma

nlapier2
Path Finder

Version 6.

0 Karma

LukeMurphey
Champion

@nlapier2: which version of Splunk are you using?

0 Karma

nlapier2
Path Finder

I have the same question as sc0tt, but I was unable to successfully implement this answer. It it compatible with Sideview's Table module? I tried replacing every instance of SimpleResultsTable with Table to no avail. Are there any other substitutions I would need to make?

0 Karma

sc0tt
Builder

I was able to get this to work as described, thanks.

0 Karma

sc0tt
Builder

Thanks, I'll check this method out as well.

0 Karma

pradeepkumarg
Influencer

You can achieve this by having custom java script code in application.js

my_app/appserver/static/js/application.js

var text = (tds[0].innerText) ? tds[0].innerText : tds[0].textContent;
.
if(text>10){ //threshold to color
{
tr.find("td:nth-child(1)").addClass("colorRed"); //colorRed is a custom css class for a table cell
}
application.css

td.colorRed{
    background-color:#CC3333;
    color: #000000;
    text-align: center 
}

sideview
SplunkTrust
SplunkTrust

by the way - that feature in the Table module was released a long time ago and I forgot to update this with a comment. Here's a pretty advanced question that uses the new feature to basically offer custom heatmap logic to color invididual table cells (but without having to understand or read any javascript).

0 Karma

sc0tt
Builder

Thanks for the clarification. It sounds like the new Table modules will be a very welcomed feature. A beta version of it would be awesome.

0 Karma

nick
Explorer

The earlier code sample posted is a rough sketch of the sort of code to use. And the example posted later using customHeatMapDecorator will only work with SimpleResultsTable, NOT Table. In the next version of Sideview Utils you will be able to give your Table modules:

<param name="columns.myFieldName.class">$myClassField$</param>
<param name="hiddenFields">myClassField</param>

and then the "myFieldName" column will get the value of the myClassField field as a class. You won't need any custom javascript at all. Can you wait a week or two? I can also email you a tar to use as a beta.

0 Karma

sc0tt
Builder

So the method described by gpradeepkumarreddy will not work unless I modify the Sideview table module?

0 Karma
Did you miss .conf21 Virtual?

Good news! The event's keynotes and many of its breakout sessions are now available online, and still totally FREE!