I was using JSONForms to render the following schema. I am using the latest ajv, using the material cells and material renderers
{
“type”: “object”,
“title”: “Person”,
“required”: [
“name”
],
“properties”: {
“name”: {
“type”: “string”,
“default”: “test”
}
}
}
<JsonForms
schema={inputJsonSchema}
data={data}
renderers={renderers}
ajv={ajv}
cells={cells}
onChange={({ data, errors }) => onChange(data, errors)}
/>
Data is just an empty object.
So the form renders with name as a text field with default value ‘test’. If I try to press the backspace to clear the text , when the field becomes empty, the default value gets set to ‘test’ again. I know we have a endAdornment to clear text, but not all users would be using that. Can you please let me know if we can set the default only on load of the form or allow clearing of the control using key strokes?
We validate every data change and AJV with useDefaults: true will always place a value into the data if it’s undefined.
If you only need to set the defaults initially, then I recommend to validate the data once outside of JSON Forms with your custom AJV and then handing in an AJV instance to JSON Forms without the useDefaults.
I tried setting the ajv outside of json forms like the following but still no luck, any sample that you could provide?
var ajv = new Ajv({ allErrors: true, strict: false, useDefaults: true, coerceTypes: true })
AjvErrors(ajv, { singleError: false })
const validate = ajv.compile(inputJsonSchema)
validate(data)
this data and schema is passed to json forms component after the following is done.
const handleFormChange1 = (data: object, errors: any) => {
console.log('data:', data) //here we get the correct data
setAppData1(data) /after this the data gets reset with defaults
console.log(errors)
}
To prevent the default value from resetting every time the field is cleared, you can apply the default value only when the form is initially loaded. One solution is to remove the "useDefaults: true" from the AJV configuration and instead manually set the default value on the form’s first render:
Initialize the data with default values before passing it to the form.
Update the data only when users make changes, allowing them to clear fields using backspace.
This prevents AJV from continuously applying the default.