Introduction

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.

Pro Tip

Formatters are used for string formatting, not manipulating the DOM and styling. Use render for that.

Custom Formatters

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.

The 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.

Validation

In addition to user input conversion, toRaw() also validates the user input during conversion. If the user input is invalid or cannot be converted to a JSON value, toRaw()MUST return 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.

SelectFormatter

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 toRaw() implementation will simply return the selected value from the DOM, which is always a string.

If you need to store a different type, you should override the formatter to provide a toRaw() implementation that returns a correct type:

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:

Using Custom Formatters

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: