How do I format a Number field in KeystoneJS?
-
23-12-2019 - |
Question
Its the property 'referenceId' that I would like to format. Heres my model code:
var keystone = require('keystone'),
Types = keystone.Field.Types;
var Stock = new keystone.List('Stock', {
map: { name: 'adminDisplayTitle' },
autocreate: true
});
Stock.add({
adminDisplayTitle: { type: String, required: true , default: 'Title to show in this Admin UI'},
referenceId: { type: Number, required: true },
country: {
type: Types.Select,
options: [
{ value: 'sv', label: 'Sweden' },
{ value: 'fi', label: 'Finland' },
{ value: 'dk', label: 'Denmark' }
],
required: true
},
author: { type: Types.Relationship, ref: 'User' },
rating: { type: String, required: true },
rate: { type: Number, required: true },
published: { type: Boolean, default: false }
});
Stock.defaultColumns = 'adminDisplayTitle, referenceId, author, createdAt';
Stock.register();
Is there any way of declaring the formatting inside the model ? I cant seem to understand the documentation for this part.
Heres an image of the field with a comma inside if it, that I want to get rid of as this is a reference id, not a value of that kind.
Solution
Number fields in KeystoneJS use the numeral.js library for formatting values.
There's an option you can set on the field to control the default format string, which can be any valid format that numeral knows what to do with, e.g:
referenceId: { type: Number, format: '0', required: true }
The Admin UI will always format the value using the string in the format
option. To remove all formatting (e.g. thousands delimiter) just set this to '0' as in the example above.
You can use the default format in your template by using the .format
underscore method on the item:
div= stockItem._.format()
The underscore method accepts a string argument which overrides the format
option set in the Model, so you can render it differently in your templates, e.g.
div= stockItem._.format('0,0');
The default format string for Number fields is '0,0[.][000000000000]'