From ee4ee862afcedfbbf4186d59548d68eede89d235 Mon Sep 17 00:00:00 2001 From: Angus Date: Mon, 1 Apr 2019 18:57:24 -0400 Subject: [PATCH] Clear dependent null fields on change --- playground/samples/null.js | 53 +++++++++++++++++++--------- src/components/fields/ObjectField.js | 22 +++++++++++- 2 files changed, 57 insertions(+), 18 deletions(-) diff --git a/playground/samples/null.js b/playground/samples/null.js index e6154e6a1e..a04fc686d6 100644 --- a/playground/samples/null.js +++ b/playground/samples/null.js @@ -3,26 +3,45 @@ module.exports = { title: "Null field example", description: "A short form with a null field", type: "object", - required: ["firstName"], properties: { - helpText: { - title: "A null field", - description: - "Null fields like this are great for adding extra information", - type: "null", + Nullable: { + type: "object", + properties: { + CarpoolInd: { + type: "boolean", + default: false, + }, + }, + dependencies: { + CarpoolInd: { + oneOf: [ + { + properties: { + CarpoolInd: { + const: true, + }, + NumPassengers: { + type: "integer", + }, + }, + required: ["NumPassengers"], + }, + { + properties: { + CarpoolInd: { + const: false, + }, + NumPassengers: { + type: "null", + }, + }, + }, + ], + }, + }, }, - firstName: { - type: "string", - title: "A regular string field", - default: "Chuck", - }, - }, - }, - uiSchema: { - firstName: { - "ui:autofocus": true, - "ui:emptyValue": "", }, }, + uiSchema: {}, formData: {}, }; diff --git a/src/components/fields/ObjectField.js b/src/components/fields/ObjectField.js index 8189536516..19e7f1ed95 100644 --- a/src/components/fields/ObjectField.js +++ b/src/components/fields/ObjectField.js @@ -9,6 +9,7 @@ import { getUiOptions, ADDITIONAL_PROPERTY_FLAG, } from "../../utils"; +import { isObject } from "../../utils"; function DefaultObjectFieldTemplate(props) { const canExpand = function canExpand() { @@ -92,7 +93,26 @@ class ObjectField extends Component { // set empty values to the empty string. value = ""; } - const newFormData = { ...this.props.formData, [name]: value }; + let newFormData = { ...this.props.formData, [name]: value }; + + // Retrieve what the schema will be after updating formData + const newSchema = retrieveSchema( + this.props.schema.properties[name], + this.props.registry.definitions, + newFormData[name] + ); + + // Set any null type fields back to null. Necessary for fields + // with dependencies that can alternate between null and another + // field type. + if (isObject(newSchema.properties)) { + Object.keys(newSchema.properties).forEach(property => { + if (newSchema.properties[property].type === "null") { + newFormData[name][property] = null; + } + }); + } + this.props.onChange( newFormData, errorSchema &&