fields.getFormatter

Since: Editor 2.0

Define a function that can transform a value being read from a field.
Please note - this property requires the Editor extension for DataTables.

Description

This option provides the ability to modify the data the end user inputs in an input element (or any other field type) transforming it into any other format before being used by the API or form submission. This can be useful for cases where you want the end user to not see the original data format.

Consider for example editing an ISO8601 date string - it isn't the friendliest format to show to your end users, so you might use fields.setFormatter to convert it to a more readable format (in combination with the datetime's format option to tell it what the format is) and then this option to convert it back to ISO8601 for the rest of your program. This use case is shown in the example below.

Note that although fields.getFormatter and fields.setFormatter are typically used together, it is not required.

Type

fields.getFormatter( value, field )

Define a function that will transform a value that is read from an input field, transforming the data into the value that will be used to submit to the server or returned via the API if using it programmatically.

Parameters:

Returns:

Any:
Formatted data that is returned - this will be seen by calls to field().val() and other methods as well as the data submitted to the server.

Example

ISO8601 date editing in readable format:

var editor = new DataTable.Editor({
	ajax: '/api/staff',
	table: '#myTable',
	fields: [
		{
			label: 'Date:',
			name: 'date',
			type: 'datetime',
			getFormatter: function (val) {
				// Convert from ddd, D MMM YY (Moment formatting) to ISO8601
				return moment(val, 'ddd, D MMM YY').format('YYYY-MM-DD');
			},
			setFormatter: function (val) {
				// Convert from ISO8601 to ddd, D MMM YY
				return moment(val, 'YYYY-MM-DD').format('ddd, D MMM YY');
			}
		}
	]
});

Related

The following options are directly related and may also be useful in your application development.