Search code examples
javascripttabulator

Tabulator 4 can I extend the formatters instead of creating a custom formatter?


Tabulator have several built-in Cell Formatters, as described in the documentation - http://tabulator.info/docs/4.0/format#format

We know that we can build a custom formatter like this:

var myCustomFormatter=function(cell, formatterParams, onRendered){
return "Mr" + cell.getValue();
}

And then use it like this in the columns parameter:

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

While tabulator formatters are "used" as strings:

{title:"Name", field:"name", formatter:"textarea"}

Our goal is to add "myCustomFormatter" to the list of available options for the parameter columns, by extending the existing formatter.

Why? We are building something dynamic, and the columns parameter will be filled with a variable that received his value from a JSON string. Something like this:

var jc='[{"title":"Name", "field":"name", "formatter":"myCustomFormatter"}]';
var c=JSON.parse(c);

var table = new Tabulator("#tbdiv", {columns: c});

But this code doesn't work as "myCustomFormatter" (as a string) is not avaiable at the formatters parameter.

Conclusion, can tabulator formatters be extended with new cell formaters (without changing the original code)?

If not, any ideias how we can fill in the columns parameter, so that it uses our custom formater?

Thanks


Solution

  • You can extend modules using the extendModule function on the Tabulator prototype:

    //add uppercase formatter to format module
    Tabulator.prototype.extendModule("format", "formatters", {
        uppercase:function(cell, formatterParams){
            return cell.getValue().toUpperCase(); //make the contents of the cell uppercase
        }
    });
    
    //use formatter in column definition
    {title:"name", field:"name", formatter:"uppercase"}
    

    You need to make sure you extend Tabulator after you have included the source files but before you create your first table.

    Full documentation for this can be found on the Tabulator Website Documentation