diff --git a/packages/ra-core/src/form/sanitizeEmptyValues.spec.ts b/packages/ra-core/src/form/sanitizeEmptyValues.spec.ts index 355d765495f..cee9660110e 100644 --- a/packages/ra-core/src/form/sanitizeEmptyValues.spec.ts +++ b/packages/ra-core/src/form/sanitizeEmptyValues.spec.ts @@ -45,6 +45,25 @@ describe('sanitizeEmptyValues', () => { sanitizeEmptyValues({ obj: { foo: null, foo2: 2 } }, { obj }) ).toEqual({ obj: { foo: { bar: 1 }, foo2: null } }); }); + it('should accept object values in arrays', () => { + const obj = [{ foo: 1 }, { foo: 2 }]; + expect(sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, {}] })).toEqual( + { obj: [{ foo: 1 }, { foo: null }] } + ); + expect(sanitizeEmptyValues({}, { obj })).toEqual({ obj }); + }); + it('should accept adding objects in arrays', () => { + const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }]; + expect( + sanitizeEmptyValues({ obj: [{ foo: 1 }, { foo: 4 }] }, { obj }) + ).toEqual({ obj: [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }] }); + }); + it('should accept removing objects in array of objects', () => { + const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }]; + expect( + sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, { foo: 4 }] }) + ).toEqual({ obj: [{ foo: 1, foo2: null }, { foo: 4 }] }); + }); it("should not ignore initial value when it's not of the same type", () => { const initialValues = { a: 'foobar' }; const values = { a: { hello: 'world' } }; diff --git a/packages/ra-core/src/form/sanitizeEmptyValues.ts b/packages/ra-core/src/form/sanitizeEmptyValues.ts index 0b54cdb2d05..bec5d15c7fb 100644 --- a/packages/ra-core/src/form/sanitizeEmptyValues.ts +++ b/packages/ra-core/src/form/sanitizeEmptyValues.ts @@ -16,8 +16,16 @@ const sanitizeEmptyValues = (initialValues: object, values: object) => { if (!initialValues) return values; const initialValuesWithEmptyFields = Object.keys(initialValues).reduce( (acc, key) => { - if (values[key] instanceof Date || Array.isArray(values[key])) { + if (values[key] instanceof Date) { acc[key] = values[key]; + } else if (Array.isArray(values[key])) { + if (Array.isArray(initialValues[key])) { + acc[key] = values[key].map((value, index) => + sanitizeEmptyValues(initialValues[key][index], value) + ); + } else { + acc[key] = values[key]; + } } else if ( typeof values[key] === 'object' && typeof initialValues[key] === 'object' &&