Form values organized by step and pre-populating related fields? #77
-
Is there a way to have Formiz separate out the form values, step by step and pre-populate related fields in another step with previous step form values? I have a Codesandbox where I'm trying to pre-populate but can't seem to get it. And also seem to be having issues with Radio options setting and updating correctly (Which is likely my lack of React skills) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
Wow .. Organizing by step is as simple as dot notation! Love it. |
Beta Was this translation helpful? Give feedback.
-
@lscmaro You can handle this use case with a custom hook like this: import { useEffect } from "react";
import { useForm } from "@formiz/core";
import get from "lodash/get";
export const useDependentField = (fieldNameOrigin, fieldNameDestination) => {
const { setFieldsValues, values, fields } = useForm({ subscribe: { fields: [fieldNameOrigin, fieldNameDestination] } });
const fieldOriginValue = get(values, fieldNameOrigin); // Needs Lodash here to handle nested fields names
const fieldDestinationPristine = get(fields, fieldNameDestination)?.isPristine; // Needs Lodash here to handle nested fields names
useEffect(() => {
// Update only if the destination field is pristine
if (fieldDestinationPristine) {
setFieldsValues({ [fieldNameDestination]: fieldOriginValue });
}
}, [
setFieldsValues,
fieldNameDestination,
fieldOriginValue,
fieldDestinationPristine
]);
}; And then you can use it like that: export const StepOne = (props) => {
const { formWizard } = props;
useDependentField("customer_info.firstname", "ship_info.firstname");
useDependentField("customer_info.lastname", "ship_info.lastname");
return (
<div className={`step-one ${formWizard.currentStep ? "isActive" : ""}`}>
<InputField
name="customer_info.firstname"
label="First Name"
required="First Name is Required"
/>
<InputField
name="customer_info.lastname"
label="Last Name"
required="Last Name is Required"
/>
</div>
);
}; There is your Codesandbox with this code 😊 Screen.Recording.2021-07-27.at.12.26.59.movI hope this can help, feel free to ask for more details if it's not clear 🤗 |
Beta Was this translation helpful? Give feedback.
@lscmaro You can handle this use case with a custom hook like this: