javascriptslickgriddataview

Slickgrid GetItemMetadata function refers only to the last item #563


I am trying to change the style of several rows with the following code block:

DV.getItemMetadata = function (row) {
  let description = this.getItem(row).Description;

  if (description != null) {
    return {
      cssClasses: 'notify'
    };
  }
  return null;
};

Here I can see that this is done correctly for all elements, but only the last element is colored.


Solution

  • I don't know exactly what your problem is but I'm showing you the code that works for me, please note that it's written with ES6 (TypeScript) syntax and you might need to change it a bit if you want to keep ES5 syntax.

    The example I got working has this code

      /** Change the Duration Rows Background Color */
      changeDurationBackgroundColor() {
        this.dataView.getItemMetadata = this.updateItemMetadataForDurationOver40(this.dataView.getItemMetadata);
    
        // also re-render the grid for the styling to be applied right away
        this.grid.invalidate();
        this.grid.render();
      }
    
      /**
       * Change the SlickGrid Item Metadata, we will add a CSS class on all rows with a Duration over 50
       * For more info, you can see this SO https://stackoverflow.com/a/19985148/1212166
       */
      updateItemMetadataForDurationOver50(previousItemMetadata: any) {
        const newCssClass = 'duration-bg';
    
        return (rowNumber: number) => {
          const item = this.dataView.getItem(rowNumber);
          let meta = {
            cssClasses: ''
          };
          if (typeof previousItemMetadata === 'object') {
            meta = previousItemMetadata(rowNumber);
          }
    
          if (meta && item && item.duration) {
            const duration = +item.duration; // convert to number
            if (duration > 50) {
              meta.cssClasses = (meta.cssClasses || '') + ' ' + newCssClass;
            }
          }
    
          return meta;
        };
      }
    

    then once you call the changeDurationBackgroundColor() from a button click it changes the background color for every row with a duration over 50.

    You can also try it yourself, here's the live Demo

    Hopefully that can help you find your problem, you might be missing the grid.invalidate() after the metadata has changed?

    enter image description here