fields.setFormatter

Since: Editor 2.0

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

Description

Normally when working with Editor you simply want to present the end user with the raw, unmodified, data for them to edit it and send it back to the database. However, there are cases where it can be useful to modify the raw data before displaying it to the end user for editing - this option provides that ability.

Consider for example editing an ISO8601 date string - it isn't the friendliest format to show to your end users, so you might use this method to convert it to a more readable format (in combination with the datetime's format option to tell it what the format is). Then use fields.getFormatter to convert it back to ISO8601 to send to the server. 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.setFormatter( value, field )

Define a function that will transform a value that is set programmatically (e.g. using field().val() or simply triggered editing on a table cell), transforming the data into the value that will be used for the input field.

Parameters:

Returns:

Any:
Formatted data that will be written into the input element for the end user to see.

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.