How to combine custom formatters with predefined formatters in Tabulator JS?
P粉676588738
P粉676588738 2023-09-13 15:40:50
0
1
736

I'm using Tabulator JS and have 2 columns containing numeric data. First, I used the built-in money formatter with formatterParams parameters, and for the second one I wanted to apply exactly the same, with the same parameters, but also add, For example, the color of the cell. How to apply formatterParams in a custom format?

new Tabulator("#data-table", {
      data: data,
      layout: "fitColumns",
      columns: [{
          title: "Length",
          field: "length",
          formatter: zeroValueFormatter,
          formatterParams: {
            thousand: " ",
            precision: false
          }
        },
        {
          title: "New length",
          field: "newLength",
          formatter: "money",
          formatterParams: {
            thousand: " ",
            precision: false
          }
        ],
      });


function zeroValueFormatter(cell, formatterParams /* ? */) {
    if (cell.getValue() === 0) {
        cell.getElement().style.backgroundColor = "#add8e6";
    }    
    return cell.getValue();
}

P粉676588738
P粉676588738

reply all(1)
P粉592085423

One option is to use rowFormatter and apply the formatting to the specific columns you need. In your example, it's length columns. This way you can use the built-in money formatter at the column setting level for both columns, but apply other formatting at the row level. Here is an example:

const data = [
  { length: 0, newLength: 10000 },
  { length: 2000, newLength: 20000 },
  { length: 3000, newLength: 0 }
]

const table = new Tabulator("#data-table", {
  data: data,
  layout: "fitColumns",
  rowFormatter: zeroValueFormatter,
  columns: [{
      title: "Length",
      field: "length",
      formatter: "money",
      formatterParams: {
        thousand: " ",
        precision: false
      }
    },
    {
      title: "New length",
      field: "newLength",
      formatter: "money",
      formatterParams: {
        thousand: " ",
        precision: false
      }
    }
  ],
});

function zeroValueFormatter(row) {
  const rowData = row.getData()

  if (rowData['length'] === 0) {
    row.getCell('length').getElement().style.backgroundColor = "#add8e6";
  }

}
<link href="https://unpkg.com/tabulator-tables@5.5.1/dist/css/tabulator.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.5.1/dist/js/tabulator.min.js"></script>
<div id="data-table"></div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template