Skip to content
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

Record form calculated fields #480

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion app/javascript/components/record-form/form/record-form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { AUDIO_FIELD, DOCUMENT_FIELD, PHOTO_FIELD } from "../constants";
import { LEGITIMATE_BASIS } from "../../record-creation-flow/components/consent-prompt/constants";
import renderFormSections from "../components/render-form-sections";
import { useApp } from "../../application";
import { parseExpression } from "../../../libs/expressions";

import { RECORD_FORM_NAME } from "./constants";
import { fieldValidations } from "./validations";
Expand Down Expand Up @@ -54,6 +55,7 @@ function RecordForm({
const formikValues = useRef();
const bindedSetValues = useRef(null);
const bindedResetForm = useRef(null);
const bindedRecalculateFields = useRef(null);

const bindSetValues = setValues => {
bindedSetValues.current = setValues;
Expand All @@ -63,6 +65,10 @@ function RecordForm({
bindedResetForm.current = resetForm;
};

const bindRecalculateFields = recalculateFields => {
bindedRecalculateFields.current = recalculateFields;
};

const buildValidationSchema = formSections => {
const schema = formSections.reduce((obj, item) => {
return Object.assign(
Expand Down Expand Up @@ -174,6 +180,14 @@ function RecordForm({
}
}, [mode.isNew, dataProtectionInitialValues]);

const calculatedFields = forms.flatMap(fs => fs.fields.filter(field => field.calculation?.expression));

useEffect(() => {
if (typeof bindedRecalculateFields.current === "function") {
bindedRecalculateFields.current();
}
});

const handleConfirm = onConfirm => {
onConfirm();
if (incidentFromCase?.size) {
Expand Down Expand Up @@ -207,11 +221,23 @@ function RecordForm({
>
{props => {
// eslint-disable-next-line react/prop-types
const { submitForm, values } = props;
const { submitForm, values, setFieldValue } = props;

bindSubmitForm(submitForm);
setFormikValuesForNav(values);

bindRecalculateFields(() => {
if (values) {
calculatedFields.forEach(field => {
const result = parseExpression(field.calculation.expression).evaluate(values);

if (values[field.name] !== result) {
setFieldValue(field.name, result, false);
}
});
}
});

return (
<FormikForm
{...props}
Expand Down
Loading