Version 6.0 Released!

Click to checkout the new features

Old Documentation
You are browsing documentation for an old version of Tabulator. Consider upgrading your project to Tabulator 6.0

Formatting The Table

Overview

Tabulator allows you to format your data in a wide variety of ways, so your tables can display information in a more graphical and clear layout.

The example below is a bit garish but it does demonstrate well how many options there are to customise your tables.

Loading Example...
Source Code

HTML

<div id="example-table"></div>

JavaScript

//Generate print icon
var printIcon = function(cell, formatterParams){ //plain text value
    return "<i class='fa fa-print'></i>";
};

//Build Tabulator
var table = new Tabulator("#example-table", {
    height:"311px",
    layout:"fitColumns",
    rowFormatter:function(row){
        if(row.getData().col == "blue"){
            row.getElement().style.backgroundColor = "#1e3b20";
        }
    },
    columns:[
    {formatter:"rownum", hozAlign:"center", width:40},
    {formatter:printIcon, width:40, hozAlign:"center", cellClick:function(e, cell){alert("Printing row data for: " + cell.getRow().getData().name)}},
    {title:"Name", field:"name", width:150, formatter:function(cell, formatterParams){
       var value = cell.getValue();
        if(value.indexOf("o") > 0){
            return "<span style='color:#3FB449; font-weight:bold;'>" + value + "</span>";
        }else{
            return value;
        }
    }},
    {title:"Progress", field:"progress", formatter:"progress", formatterParams:{color:["#00dd00", "orange", "rgb(255,0,0)"]}, sorter:"number", width:100},
    {title:"Rating", field:"rating", formatter:"star", formatterParams:{stars:6}, hozAlign:"center", width:120},
    {title:"Driver", field:"car", hozAlign:"center", formatter:"tickCross", width:50},
    {title:"Col", field:"col" ,formatter:"color", width:50},
    {title:"Line Wraping", field:"lorem" ,formatter:"textarea"},
    {formatter:"buttonCross", width:30, hozAlign:"center"}
    ],
});

Cell Formatters

You can set cell formatters on a per column basis using the formatter option in the column definition object.

You can pass an optional additional parameter with the formatter, formatterParams that should contain an object with additional information for configuring the formatter.

{title:"Name", field:"name", formatter:"star", formatterParams:{stars:6}}

Params Lookup Function

If you want to dynamically generate the formatterParams at the time the formatter is called you can pass a function into the property that should return the params object.

//define lookup function
    function paramLookup(cell){
    //cell - the cell component

    //do some processing and return the param object
    return {param1:"green"};
}

//column definition
{title:"Name", field:"name", formatter:"star", formatterParams:paramLookup}

Built In Formatters

Tabulator comes with a number of preconfigured formatters, which are outlined below.

To guard against code injection, any formatters that are meant to display text (plaintext, textarea, money, email, link) have the data sanitized first to escape any potentially harmful HTML or JavaScript from making into the table, this causes any such data to be displayed as its plain text alternative. If you want the HTML to be displayed correctly use the html formatter, but be aware if your data can be user edited this could allow for malicious script injection.

Note: For a guide to adding your own formatters to this list, have a look at the Extending Tabulator section.

Plain Text

The plaintext formatter is the default formatter for all cells and will simply dispay the value of the cell as text.

{title:"Example", field:"example", formatter:"plaintext"}

Text Area

The textarea formatter shows text with carriage returns intact (great for multiline text), this formatter will also adjust the height of rows to fit the cells contents when columns are resized.

{title:"Example", field:"example", formatter:"textarea"}

HTML

The html formatter displays un-sanitized html.

{title:"Example", field:"example", formatter:"html"}

Money

The money formatter formats a number into currency notation (eg. 1234567.8901 -> 1,234,567.89).

{title:"Example", field:"example", formatter:"money", formatterParams:{
    decimal:",",
    thousand:".",
    symbol:"£",
    symbolAfter:"p",
    precision:false,
}}

The formatter has optional properties for the formatterParams object:

  • decimal - Symbol to represent the decimal point (default ".")
  • thousand - Symbol to represent the thousands separator (default ",")
  • symbol - currency symbol (no default)
  • symbolAfter - position the symbol after the number (default false)
  • precision - the number of decimals to display (default is 2), setting this value to false will display however many decimals are provided with the number

Image

The image formatter creates an img element with the src set as the value. (triggers the normalizeHeight function on the row on image load).

{title:"Example", field:"example", formatter:"image", formatterParams:{
    height:"50px",
    width:"50px",
}}

The formatter has optional properties for the formatterParams object:

  • height - a CSS value for the height of the image
  • width - a CSS value for the width of the image

Link

The link formatter renders data as an anchor with a link to the given value (by default the value will be used as both the url and the label of the tag).

{title:"Example", field:"example", formatter:"link", formatterParams:{
    labelField:"name",
    urlPrefix:"mailto://",
    target:"_blank",
}}

The formatter has optional properties for the formatterParams object:

  • labelField - the field in the row data that should be used for the link label
  • label - a string representing the label, or a function which must return the string for the label, the function is passed the Cell Component as its first argument
  • urlPrefix - a prefix to put before the url value (eg. to turn a emaill address into a clickable mailto link you should set this to "mailto:")
  • urlField - the field in the row data that should be used for the link url
  • url - a string representing the url, or a function which must return the string for the url, the function is passed the Cell Component as its first argument
  • target - a string representing the value of the anchor tags target artibute (eg. set to "_blank" to open link in new tab)
  • download - treat the link as a download instead of opening in the browser (default:false), this can take three different types of value:
    • true - a boolean value of true will mark the link as a download and use the filename provided by the server
    • string - a string for the filename of the downloaded file
    • function - a callback that will be passed in the cell component as an argument and should return the file name for the downloaded file

Date Time

The datetime formatter transforms on format of date or time into another.

{title:"Example", field:"example", formatter:"datetime", formatterParams:{
    inputFormat:"YYYY-MM-DD HH:ii",
    outputFormat:"DD/MM/YY",
    invalidPlaceholder:"(invalid date)",
    timezone:"America/Los_Angeles",
}}

You will need to include the moment.js library to use this sorter

The formatter has optional properties for the formatterParams object:

  • inputFormat - the format of the date/time in the row data(default: YYYY-MM-DD HH:mm:ss)
  • outputFormat - the format of the date/time to be displayed (default: DD/MM/YYYY HH:mm:ss)
  • invalidPlaceholder - the value to be displayed if an invalid input date/time is provided (default:""), this can take three different types of value:
    • true - a boolean of true will display the cells original value
    • function - a function passed into this will be called with the original value of the cell passed into its first argument
    • string/number - a string on number will be displayed instead of the cells value
  • timezone - set the timezone for the datetime, it will accept any valid Moment Timezone. In order to use this property you must include the Moment Timezone library in your project, in addition to moment.js

Date Time Difference

The datetimediff show difference between two datetimes.

{title:"Example", field:"example", formatter:"datetimediff", formatterParams:{
    inputFormat:"YYYY-MM-DD",
    humanize:true,
    invalidPlaceholder:"(invalid date)",
}}

You will need to include the moment.js library to use this sorter

The formatter has optional properties for the formatterParams object:

  • inputFormat - the format of the date/time in the row data(default: YYYY-MM-DD HH:mm:ss)
  • date - a moment object of the data to compare against (defaults to the current date time)
  • humanize - if set to true diff will be displayed in a human readable fashion (eg "10 days") (default: false)
  • unit - the time using for the difference (years, months, weeks, days, hours, minutes, seconds). This property will be ignored if humanize is used (default:seconds)
  • suffix - if humanize is used setting this to true will make times relative (eg "10 days ago"). if humanize is not used the string passed to this will be appended after the difference value (default:false)
  • invalidPlaceholder - the value to be displayed if an invalid input date/time is provided (default:""), this can take three different types of value:
    • true - a boolean of true will display the cells original value
    • function - a function passed into this will be called with the original value of the cell passed into its first argument
    • string/number - a string on number will be displayed instead of the cells value

Tick Cross

The tickCross formatter displays a green tick if the value is (true|'true'|'True'|1) and a red cross if not.

{title:"Example", field:"example", formatter:"tickCross", formatterParams:{
    allowEmpty:true,
    allowTruthy:true,
    tickElement:"<i class='fa fa-check'></i>",
    crossElement:"<i class='fa fa-times'></i>",
}}

The formatter has optional properties for the formatterParams object:

  • allowEmpty - set to true to cause empty values (undefined, null, "") to display an empty cell instead of a cross (default false)
  • allowTruthy - set to true to allow any truthy value to show a tick (default false)
  • tickElement - custom HTML for the tick element, if set to false the tick element will not be shown (it will only show crosses)
  • crossElement - custom HTML for the cross element, if set to false the cross element will not be shown (it will only show ticks)

Color

The color formatter sets the background colour of the cell to the value. The cell's value can be any valid CSS color eg. #ff0000, #f00, rgb(255,0,0), red, rgba(255,0,0,0), hsl(0, 100%, 50%)

{title:"Example", field:"example", formatter:"color"}

Star Rating

The star formatter displays a graphical star rating based on integer values.

{title:"Example", field:"example", formatter:"star", formatterParams:{
    stars:8,
}}

The formatter has optional properties for the formatterParams object:

  • stars - maximum number of stars to be displayed (default 5)

Traffic Light

The traffic formatter displays a coloured circle that changes colour depending on the numeric value of the cell. No image will be displayed if the cells value is undefined or not a valid number

{title:"Example", field:"example", formatter:"traffic", formatterParams:{
    min:0,
    max:10,
    color:["green", "orange", "red"],
}}

The formatter has optional properties for the formatterParams object:

  • min - minimum value for progress bar (default 0)
  • max - minimum value for progress bar (default 100)
  • color - colour of progress bar (default ["red", "orange", "green"]), this can be:
    • array of strings - an array of color strings, that will divide the background colour across the min-max range of values(eg ["green", "orange", "#ff0000"])
    • function - a callback that is passed the value of the cell and must return the color (eg function(value){return "red"})

Progress Bar

The progress formatter displays a progress bar that fills the cell from left to right, using values 0-100 as a percentage of width.

{title:"Example", field:"example", formatter:"progress", formatterParams:{
    min:0,
    max:10,
    color:["green", "orange", "red"],
    legendColor:"#000000",
    legendAlign:"center",
}}

The formatter has optional properties for the formatterParams object:

  • min - minimum value for progress bar (default 0)
  • max - minimum value for progress bar (default 100)
  • color - colour of progress bar (default #2DC214), this can be:
    • string - any valid css color string (eg "#fff000")
    • array of strings - an array of color strings, that will divide the background colour across the min-max range of values(eg ["green", "orange", "red"])
    • function - a callback that is passed the value of the cell and must return the bar color (eg function(value){return "red"})
  • legend - a text value to display over the progress bar, this can be:
    • string - any string
    • true - if set to true this will show the value of the cell
    • function - a callback that is passed the value of the cell and must return the legend contents (eg function(value){return value + "%"})
  • legendColor - the text colour for the legend, has the same range of value options as the color property
  • legendAlign - the text alignment for the legend, this can be:
    • center - center align text (default)
    • left - left align text
    • right - right align text
    • justify - stretch out text to fit line

List Lookup

The lookup formatter looks up the value to display from a object passed into the formatterParams property, if not present it displays the current cell value

{title:"Example", field:"example", formatter:"lookup", formatterParams:{
    "small": "Cute",
    "medium": "Fine",
    "big": "Scary",
}}

To use this formatter you need to pass an object to formatterParams where the initial value of the cell is the property key and the value to be displayed is the property value (eg {"blue":"black", "red":"green"}, would change the value "blue" to "black", and the value "red" to "green")

Tick Button

The buttonTick formatter displays a tick icon on each row (for use as a button)

{title:"Example", field:"example", formatter:"buttonTick"}

Cross Button

The buttonCross formatter displays a cross icon on each row (for use as a button)

{title:"Example", field:"example", formatter:"buttonCross"}

Row Number

The rownum formatter shows an incrementing row number for each row as it is displayed

{title:"Example", field:"example", formatter:"rownum"}

Sorting / Filtering
Row numbers only refer to the current position of the row in the table. Sorting or filtering the table will result in row numbers being reallocated to ensure the order remains consistent.

Row Handle

The handle formatter fills the cell with hamburger bars, to be used as a row handle

{title:"Example", field:"example", formatter:"handle"}

Module Formatters

There are a number of special formatters that are tied to specific module functionally. These formmatters should only be used in conjunction with the specified modules.

Row Selection

The rowSelection formatter allows you to add a column of tickboxes down one side of your table to handle row selection, when used as a titleFormatter it provides a tickbox that can toggle the selection of all rows in the table

{formatter:"rowSelection", titleFormatter:"rowSelection", hozAlign:"center", headerSort:false}

For more information on when to use this formatter, checkout the Row Selection Documentation

Responsive Collapse List Show/Hide

If you would like your users to be able to interact with the list and hide/show it as needed you can add a column that uses the built-in responsiveCollapse formatter that provides a control for toggling the visibility of the collapsed list

{formatter:"responsiveCollapse", headerSort:false}

The column using this formatter will be automatically hidden when there are no collapsed columns to display.

For more information on when to use this formatter, checkout the Responsive Collapse Documentation

Custom Formatters

As well as the built-in formatters you can define a formatter using a custom formatter function.

The formatter function accepts two arguments, the CellComponent for the cell being formatted and the formatterParams option from the column definition.

The function must return the contents of the cell, either the text value of the cell, valid HTML or a DOM node.

{title:"Name", field:"name", formatter:function(cell, formatterParams, onRendered){
    //cell - the cell component
    //formatterParams - parameters set for the column
    //onRendered - function to call when the formatter has been rendered

    return "Mr" + cell.getValue(); //return the contents of the cell;
},
}

Formatters vs Mutators
An important difference between a formatter and a mutator is that a formatter will only alter how data is displayed in cells but will not affect the data itself, while a mutator will alter the data contained in the table, which will then be visible in the data retrieved using the getData function. (see Mutators for more details)

Triggering Actions After the Formatter Has Been Displayed

The formatter code is run before the element is added to the DOM, on the whole this is not a problem, but some other libraries require the element they are attached to to be visible before they are run. To do this Tabulator provides the onRendered callback function.

To use this function you need to pass a callback that runs any of your required code as the only argument. The example below uses the jQuery sparkline widget to format data into a chart

var sparklineFormatter = function(cell, formatterParams, onRendered){
    onRendered(function(){
    $(cell.getElement()).sparkline(cell.getValue(), {width:"100%", type:"bar"});
});
};

Variable Height Formatters

By default formatters will keep their contents within the height of the current row, hiding any overflow. The only exception to this is the textarea formatter which will automatically vary its height when the column is resized so its contents does not overflow.

If you would like this functionally to appear in another type of formatter you can set the variableHeight property to true in the column definition and it will will behave in a similar way to the textarea formatter:

{title:"Name", field:"name", formatter:myCustomFormatter, variableHeight:true}

Column Header Title Formatters

You can use formatters to layout your column titles using the titleFormatter and titleFormatterParams options in a column's defintition object:

These work in exactly the same way as the formatter and formatterParams options and accept the same Formatters

//column definition in the columns array
{title:5, field:"rating", titleFormatter:"star", titleFormatterParams:{stars:5}},

Params Lookup Function

If you want to dynamically generate the titleFormatterParams at the time the formatter is called you can pass a function into the property that should return the params object.

//define lookup function
function paramLookup(){
    //do some processing and return the param object
    return {param1:"green"};
}

//column definition
{title:5, field:"rating", titleFormatter:"star", titleFormatterParams:paramLookup}

Export Formatting

When exporting data from a table by printing, using the clipboard or using the getHTML function, you may want to apply a different formatter from the one usualy used to format the cell.

There are differnt formatter properties for each type of export:

  • formatterPrint - Formatter to be used when printing
  • formatterClipboard - Formatter to be used when copying to the clipboard
  • formatterHtmlOutput - Formatter to be used when the getHtml function is called

Each export formatter function has its own matching params option, for example formatterPrint has formatterPrintParams.

These properties take the same inputs as the standard formatter property

//define print formatter
function printFormatter(cell, formatterParams, onRendered){
    return cell.getValue() ? "YES" : "NO";
}

//column definition
{title:"Driver", field:"driver", formatter:"tickCross", formatterPrint:printFormatter} //show "YES"/"NO" in the cell when printing

Disable Standard Formatter on Export

Passing a value of false into an export formatter will cause the value to be shown as plain text without a formatter

{title:"Driver", field:"driver", formatter:"tickCross", formatterPrint:false} //show as plain text when printing

Icon/Button Columns

You can create icon/button columns, by not specifying the field option in the column definition object and creating a custom formatter for the column contents. In the example below we have created a print button on the left of each row.

//custom formatter definition
 var printIcon = function(cell, formatterParams, onRendered){ //plain text value
    return "<i class='fa fa-print'></i>";
};

//column definition in the columns array
{formatter:printIcon, width:40, hozAlign:"center", cellClick:function(e, cell){alert("Printing row data for: " + cell.getRow().getData().name)}},

Row Formatting

Tabulator also allows you to define a row level formatter using the rowFormatter option. this lets you alter each row of the table based on the data it contains.

The function accepts one argument, the RowComponent for the row being formatted.

The example below changes the background colour of a row to blue if the col value for that row is "blue".

var table = new Tabulator("#example-table", {
    rowFormatter:function(row){
        //row - row component

        var data = row.getData();

        if(data.col == "blue"){
            row.getElement().style.backgroundColor = "#1e3b20";
        }
    },
});

Re-Format Row

If you want to re-format a row once it has been rendered to re-trigger the cell formatters and the rowFormatter callback, Call the reformat function on its Row Component.

row.reformat();

Export Formatting

When exporting data from a table by printing, using the clipboard or using the getHTML function, you may want to apply a different formatter from the one usualy used to format the row.

There are differnt formatter properties for each type of export:

  • rowFormatterPrint - Formatter to be used when printing
  • rowFormatterClipboard - Formatter to be used when copying to the clipboard
  • rowFormatterHtmlOutput - Formatter to be used when the getHtml function is called

These properties take the same inputs as the standard rowFormatter property.

var table = new Tabulator("#example-table", {
    rowFormatter:function(row){
        //row - row component

        var data = row.getData();

        if(data.col == "blue"){
            row.getElement().style.backgroundColor = "#1e3b20";
        }
    },
    rowFormatterPrint:function(row){
        //row - row component

        var data = row.getData();

        if(data.col == "blue"){
            row.getElement().style.backgroundColor = "#0000ff"; //use a different shade of blue background when printing
        }
    },
});

Disable Standard Formatter on Export

Passing a value of false into an export formatter will cause the value to be shown as plain text without a formatter

var table = new Tabulator("#example-table", {
    rowFormatter:function(row){
        //row - row component

        var data = row.getData();

        if(data.col == "blue"){
            row.getElement().style.backgroundColor = "#1e3b20";
        }
    },
    rowFormatterPrint:false, //disable standard formatter when printing
});

ToolTips

You can set tooltips to be displayed when the cursor hovers over cells. By default, tooltips are not displayed.

Tooltips can either be set globally using the tooltips options parameter:

var table = new Tabulator("#example-table", {
    tooltips:true,
});

Or on a per column basis in the column definition array:

//column definition in the columns array
{formatter:printIcon, width:40, hozAlign:"center", tooltip:true},

The tooltip parameter can take three different types of value

  • boolean - a value of false disables the tooltip, a value of true sets the tooltip of the cell to its value
  • string - a string that will be displayed for all cells in the matching column/table.
  • function - a callback function that returns the string for the cell. see below:

The function accepts one argument, the CellComponent for the cell the tooltip is being generated for.

var table = new Tabulator("#example-table", {
    tooltips:function(cell){
        //cell - cell component

        //function should return a string for the tooltip of false to hide the tooltip
        return  cell.getColumn().getField() + " - " + cell.getValue(); //return cells "field - value";
    },
});

Note: setting a tooltip value on a column will override the global setting.

Tooltip Generation Mode

By default Tabulator regenerates tooltips whenever data in a cell changes, however if you use a tooltip generation function that is dependent on values outside the cell this may mean the tooltip does not update as expected.

To get round this, you can use the tooltipGenerationMode parameter to make tooltips regenerate whenever the users mouse enters the cell. The parameter can have one of two values

  • load - Generate tooltip when value is loaded into cell (default behaviour)
  • hover - Generate tooltip when users mouse enters the cell
var table = new Tabulator("#example-table", {
    tooltipGenerationMode:"hover", //regenerate tooltip as users mouse enters the cell;
});

Column Header ToolTips

It is also possible to set tooltips to display on the column headers. This is particularly useful when your columns are too narrow to display full header names.

Header tooltips can either be set globally using the tooltipsHeader options parameter:

var table = new Tabulator("#example-table", {
    tooltipsHeader:true, //enable header tooltips
});

Or on a per column basis in the column definition array:

//column definition in the columns array
{title:"name", field:"name", width:40, hozAlign:"center", headerTooltip:true},

The tooltip headerTooltip can take three different types of value

  • boolean - a value of false disables the tooltip, a value of true sets the tooltip of the column header to its title value.
  • string - a string that will be displayed for the tooltip.
  • function - a callback function that returns the string for the column header. see below:

The function accepts one argument, the ColumnComponent for the column the tooltip is being generated for.

var table = new Tabulator("#example-table", {
    tooltips:function(column){
        //column - column component

        //function should return a string for the header tooltip of false to hide the tooltip
        return  column.getDefinition().title;
    },
});

Note: setting a headerTooltip value on a column will override the global setting.

Donate