Quickie: Changing background-color of table view cells depending on content

For security reasons AppGini filters out CSS styles if injected into HTML code using PHP hook function. In this article you will find an easy-to-use, depencdency-free javascript fuction for changing background-color of table view cells depending on cell's value.

Common function

Place the following function in <script>...</script> tags in hooks/header-extras.php, for example, so you can re-use it in any table view later on.

function AppGiniTableViewBackgroundChanger(cn, options) {
  jQuery(function() {
    const options_lc = Object.fromEntries(Object.entries(options).map(([key, val]) => [key.toLowerCase(), val]));
    jQuery(`tr[data-id] > td.${AppGini.currentTableName()}-${cn}`).each(function(i, e) {
                jQuery(e).css('background-color', options_lc[jQuery(e).text().trim().toLowerCase()]);
    });
  });
}

Usage

For a specific table view, create a javascript hooks file named /hooks/TABLENAME-tv.js, if not already exists. In there call the function shown above.

AppGiniTableViewBackgroundChanger("COLUMNNAME", {
  "State1": "red",
  "State2": "yellow",
  "State3": "green",
});

Parameters:

  1. column name (string)
  2. object having states (as keys) and background-colors (as values).

The example above will find all cells of column COLUMNNAME and will set the background-color depending on the cell's text. If, for example, cell's text equals "State1", the background-color will be red. The comparison is case-insensitive, which means, also "state1" and "STATE1" would match and coloured red.

Example

AppGiniTableViewBackgroundChanger("type_id", {
  "Bauabnahme": "orange",
  "Auslieferung": 'red',
});

AppGiniTableViewBackgroundChanger("description", {
  "test": "lightblue",
});

AppGiniTableViewBackgroundChanger("order_id", {
  "1": "red",
  "2": "yellow",
  "3": "green",
});

Output

Do you like it?