In Backgrid, cell formatters serves the purpose of converting values between JSON value types and strings, and validation. Writing formatters for value conversion and validation is easy as you only have to conform to a very simple protocol.
Formatters are used for string formatting, not manipulating the DOM and styling. Use render for that.
Any formatters must have the following two methods defined:
fromRaw() is called by Backgrid.Cell and its
subclasses whenever a raw model value needs to be formatted into
a humanized form for display.
toRaw() is called by Backgrid.CellEditor and its
subclasses whenever a user input string needs to be converted back
to a raw JSON value for model persistence.
model parameter is not used by any built-in
formatters, but sometimes you may want to decide how to format your
values depending on the other values in the model. You can use it in
your custom formatters if that's the case.
In addition to user input conversion,
validates the user input during conversion. If the user input is
invalid or cannot be converted to a JSON value,
undefined instead of throwing an Error.
In addition to using formatters to do simple yes or no validations, if your model class has a validate() method defined, it will also be used for validation after trying with the formatter.
The most common formatter you'll override is probably
SelectFormatter. Suppose your column expects an integer, due to a
limitation of the DOM, the default
will simply return the selected value from the DOM, which is always a
If you need to store a different type, you should override the
formatter to provide a
toRaw() implementation that returns a
If you want to use a SelectCell with multiple select, and if the type
of your model value is not string, you have to override
toRaw to return an array of values:
A custom formatter supplied to a column definition will be used instead of the cell's default:
To make your custom cell and custom formatter reuseable, you can package them up together and give your custom cell to a column definition: