How can I programmatically change the value of a field? #171
-
Hi! I have a button, that when clicked, it would change / prefill certain inputs. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
Hi @MoSattler, there are 2 approaches you can try: // Approach 1 - Controlled input
const [value, setValue] = useState();
// Just set the state on button click
<input value={value} onChange={event => setValue(event.target.value)} />
<button type="button" onClick={() => setValue('something')}>Action</button>
// Approach 2 - Update the input value with useInputEvent
// This will also emit a change / input event and trigger validation based on your form's configuration.
const [ref, control] = useInputEvent();
<input ref={ref} />
<button type="button" onClick={() => control.change('something')}>Action</button> |
Beta Was this translation helpful? Give feedback.
-
@edmundhung, a common use case is to populate many fields with a call to action. For example, calculate something with the current fields to fill other fields automatically. With your suggestions, it is not possible to set values outside the field components. Therefore, it would be nice to have something like this: form.setValues({
field1: "foo",
feld2: "bar"
}) To have something like this is not a comfortable option since we would need one hook per field: const {setValue1} = useField("field1")
const {setValue2} = useField("field2") I just find out that this is updating the form values but not the input values, so this is not working: const form = useFormMetadata("formId");
form.update({ value: { myInputName: "newValue" } }); As a workaround, I'm using a global store with Zustand to save all the controlled input values and then modify them globally. But I consider that option not so elegant. |
Beta Was this translation helpful? Give feedback.
Hi @MoSattler, there are 2 approaches you can try: