Set field values programatically when using useForm

In the context of an UIKit application, is there a way to set a value of a field “controlled” by useForm ?

I want to present dynamically computed list of suggestions and I want the user to be able to click on a button to set the value instead of having to click on the field and find the correct value.

Is this achievable or do I have to opt out of useForm ?

1 Like

I’m not sure your exact use case, but if you want it to be completely controlled, I believe you can use getValues with the name of the controlling element and use it to set the value of the controlled element. Something like this:

const { getValues, register } = useForm();
return (
  <Textfield
    name="controlling"
    {...register("controlling", {
      required: true,
    })}
  />
  <Textfield
    name="controlled"
    value={getValues("controlling")}
  />
)

Note that this won’t work when you use register for elements, since that overrides the value and onChange props. And you can’t get the controlled value from getValues. So I think having it be partly controlled and partly not would be difficult if not impossible.

Hello @AaronCollier,

Thanks for this solution.

My issue is to be able to change programmatically the value of a field that is handled by useForm. In your example, that would be setting the value of the ‘controlling’ field.

If you use register from useForm, it adds its own value property for the field, so I don’t think that can be overridden.