Search code examples
javascriptslickgrid

Slickgrid use a column to contain the color for each row?


Is it possible to add a hidden column to my grid to store a hex color. Then use the value in this column to style the background color of that row?


Solution

  • Styling of an entire row is most intuitively accomplished by providing metadata to the grid regarding individual rows. When using the Slickgrid Dataview, this becomes slightly more challenging due to the potential need to support grouping, as the groups provide some information via their own groupItemMetadataProvider. Similiar to the information provided here a few options are available. Attempting to format each cell, leaves some visible whitespace and can cause issue with empty cells.

    As such, I would provide corresponding css classes for each color you'll be supporting. Setup the getItemMetadata to return the respective css for each row.

    var defaultImpl = dataView.getItemMetadata
    
    var override = function(row){
        
      if(!defaultImpl(row)) {
       var item = dataView.getItem(row)
       /*
         assuming the color is stored similar to #000000 ... strip off the #
         in addition I've prefixed my css classes with 'color_'
       */ 
       var color = item.color ? 'color_' + item.color.substr(1, item.color.length) : ""
       var metadata = item.color ? {cssClasses: color} : null
       return metadata
      }
       return defaultImpl(row)
    }
    
    dataView.getItemMetadata = override
    

    Note: Any styling attempts outside the context available to the grid will get wiped upon scrolling.

    Fiddle