-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix null value support in inputs #8262
Conversation
@@ -7,7 +7,7 @@ | |||
export const sanitizeEmptyValues = (values: any, record: any = {}): any => { | |||
const sanitizedValues = {}; | |||
Object.keys(values).forEach(key => { | |||
if (values[key] === '') { | |||
if (values[key] == null || values[key] === '') { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't understand why you updated this function
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For react-admin inputs (such as TextInput), when the field is undefined
from the dataProvider:
- if you touch the field (e.g. change it to
'foo'
then back to''
) - if your field has a defaultValue but you clear it
=> In both cases we will send"field": null
, although the field was absent from what the dataProvider returned.
This is because sanitizeEmptyValues only triggers on ''
but not on null
, however our components now return null
.
IMO in this case sanitizeEmptyValues should still remove the values from what's been sent (hence my change of the implementation is needed).
I'll add a story to play with this to the branch in any case so that you can see for yourself 😉
Problem:
Because of https://github.com/marmelab/react-admin/blob/master/packages/ra-core/src/form/getFormInitialValues.ts#L16,
null
values in records get transformed into empty strings''
.We should not change the records value like this, especially if the user does not change them in a form.
This also prevents to submit
null
as value.Actually, adding a
parse
prop likeparse={value => (value === '' ? null : value)}
actually works, but only if the value is changed by the user.Solution:
getFormInitialValues
, and instead add a defaultformat
function to all inputs (viauseInput
) to change the formatted value to an empty string in that case, but not the actual (controlled) value.parse
function to all inputs to parse all empty strings tonull
, because that's what most backends expect anywayAdditional info
sanitizeEmptyValues
is now rendered mostly useless when using only RA input components (such as TextInput, NumberInput, ...) ; it remains useful however if you are using custom inputs that do not useuseInput
useInput
will need to format their value to''
when they receiveundefined
ornull
by themselves, otherwise this will raise console warnings about controlled/uncontrolled inputs