Skip to content

Commit fddd3c9

Browse files
authored
Merge pull request #480 from awensaunders/record-form-calculated-fields
Record form calculated fields
2 parents a833842 + 74bf634 commit fddd3c9

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

app/javascript/components/record-form/form/record-form.jsx

+27-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { AUDIO_FIELD, DOCUMENT_FIELD, PHOTO_FIELD } from "../constants";
1818
import { LEGITIMATE_BASIS } from "../../record-creation-flow/components/consent-prompt/constants";
1919
import renderFormSections from "../components/render-form-sections";
2020
import { useApp } from "../../application";
21+
import { parseExpression } from "../../../libs/expressions";
2122

2223
import { RECORD_FORM_NAME } from "./constants";
2324
import { fieldValidations } from "./validations";
@@ -54,6 +55,7 @@ function RecordForm({
5455
const formikValues = useRef();
5556
const bindedSetValues = useRef(null);
5657
const bindedResetForm = useRef(null);
58+
const bindedRecalculateFields = useRef(null);
5759

5860
const bindSetValues = setValues => {
5961
bindedSetValues.current = setValues;
@@ -63,6 +65,10 @@ function RecordForm({
6365
bindedResetForm.current = resetForm;
6466
};
6567

68+
const bindRecalculateFields = recalculateFields => {
69+
bindedRecalculateFields.current = recalculateFields;
70+
};
71+
6672
const buildValidationSchema = formSections => {
6773
const schema = formSections.reduce((obj, item) => {
6874
return Object.assign(
@@ -174,6 +180,14 @@ function RecordForm({
174180
}
175181
}, [mode.isNew, dataProtectionInitialValues]);
176182

183+
const calculatedFields = forms.flatMap(fs => fs.fields.filter(field => field.calculation?.expression));
184+
185+
useEffect(() => {
186+
if (typeof bindedRecalculateFields.current === "function") {
187+
bindedRecalculateFields.current();
188+
}
189+
});
190+
177191
const handleConfirm = onConfirm => {
178192
onConfirm();
179193
if (incidentFromCase?.size) {
@@ -207,11 +221,23 @@ function RecordForm({
207221
>
208222
{props => {
209223
// eslint-disable-next-line react/prop-types
210-
const { submitForm, values } = props;
224+
const { submitForm, values, setFieldValue } = props;
211225

212226
bindSubmitForm(submitForm);
213227
setFormikValuesForNav(values);
214228

229+
bindRecalculateFields(() => {
230+
if (values) {
231+
calculatedFields.forEach(field => {
232+
const result = parseExpression(field.calculation.expression).evaluate(values);
233+
234+
if (values[field.name] !== result) {
235+
setFieldValue(field.name, result, false);
236+
}
237+
});
238+
}
239+
});
240+
215241
return (
216242
<FormikForm
217243
{...props}

0 commit comments

Comments
 (0)