I have made some simply setups pages with formio form builder which uses the custom builder and then made an additional page view where you can edit the form.
When creating the form using the form builder as such
<FormBuilder options={options} onChange={onFormChange}/>
it works fine and catches the change
But when trying to use it as edit as such where it simply loads in the schema created by the form builder like such
<FormBuilder initialForm={schema} options={options} onChange={onFormChange}/>
It doesn't catch any of the changes made in the form. It loads the form fine and I can edit it. But it will not trigger the onChange. If I remove the initialForm it works fine.
I tried with just the hardcoded schema and using the schema passed as the JSON created by the builder.
It seems to fine if the initialForm is passed as empty object or string but not a full schema.
Anyone got an idea what is going or is it simply a bug on the formBuilder?
Don't update the state variable (schema) that is assigned to initialForm
, as it means to provide only the initial state of the form, not to hold the further changes.
const onFormChange = (schema) => {
❌setSchema(schema); //---------------------- Don't do this
console.log("Form schema changed: ", schema);
};
Instead, a separate state variable can be used to track all the changes.
const schema2 = {....}; // Original form schema
// Introduce the new empty variable
const [formObj, setFormObj] = useState({});
// Put the form changes into formObj state variable
const onFormChange = (updatedSchema) => {
console.log("Form schema changed: ", updatedSchema);
setFormObj(updatedSchema);
};
// JSX
<FormBuilder
initialForm={schema2}
options={options}
onChange={onFormChange}
/>
Eventually formObj
will contain all the changes, i.e initial form + latest changes. You may access the changed components from formObj.components
array.