Search code examples
jquery-bootgrid

jQuery Bootgrid Conditional Icon in Header Cell


I'd like to add an icon to the header cell if a condition is met. I know that in the documentation it mentions that dynamic placholders are a thing, but it doesn't elaborate on how to add your own.


What I've tried:

Defining my own Template:

templates: {
    headerCell: '<th data-column-id="{{ctx.column.id}}">{{ctx.column.text}}{{ctx.column.myCustomIcon}}</th>',
}

then in the formatters, adding the custom field.

formatters: {
  myCustomField: function(column, row){

    column.myCustomIcon = "";

    if (item[column.id] == 0) {
      return "";
    }

    column.myCustomIcon = '<i class="fa fa-shield"></i>';
  }
}

Doesn't work, some guidance would be appreciated.


Solution

  • I managed to do this without using template, plus creating a new method in their prototype.

    Just add this method in their library (jquery.bootgrid.js):

    Grid.prototype.recreateTableHeader = function () {
        renderTableHeader.call(this);
        return this;
    };
    

    This must be placed after they define var Grid = function(element, options) around line 974.

    Then, you can call this method after the grid is loaded:

    var columnNameChanged = false;
    
    var grid = $('#my-grid').bootgrid(/* your options here */);
    
    grid.on("loaded.rs.jquery.bootgrid", function () {
    
        if (!columnNameChanged) {
    
            columnNameChanged = true;
            var columns = grid.bootgrid('getColumnSettings');
            var column = columns[1];
            column.text = '<i class="fa fa-shield"></i> ' + column.text;
    
            grid.bootgrid('recreateTableHeader');
        }
    
    });
    

    Take note I'm changing the column's text property, concatenating the icon with the current column.text (which holds the text you put in your HTML). You can change this inside your formatter or inside this loaded event like my sample, but since your formatter is called once for each row and I'm appending the column.text after the icon markup, you'd end up having a column text like <i class="fa fa-shield"></i><i class="fa fa-shield"></i><i class="fa fa-shield"></i> Column Name.