form icon indicating copy to clipboard operation
form copied to clipboard

[Feature Request]: Transform values on submit

Open crutchcorn opened this issue 1 year ago • 6 comments

This feature request comes from https://github.com/houseform/houseform/issues/60, the older form library I maintained

Description

Ideally, I'd like to have a number, displayed as a string (say, a locale with 1,000,000) and then transform this number back during the field submission.

 <Field
  name="number"
  initialValue={'0'}
  // This is the magic
  transformOnSubmit={v => parseFloat(v)}
  onChangeValidate={z.coerce.number().min(1, 'Must be at least 1')}
/>

crutchcorn avatar Aug 30 '23 14:08 crutchcorn

Hey @crutchcorn, mind assigning me this for me to work on? 🙏

CheRayLiu avatar Sep 08 '23 02:09 CheRayLiu

Done! Thanks for taking this on @CheRayLiu.

Something worth considering is how we will/should handle TypeScript typings for transformations.

crutchcorn avatar Sep 08 '23 02:09 crutchcorn

Unassigned myself for now as I don't see myself working on it any time soon

CheRayLiu avatar Dec 04 '23 19:12 CheRayLiu

No worries @CheRayLiu! Thanks for being willing in the first place :)

crutchcorn avatar Dec 04 '23 19:12 crutchcorn

Just an idea for this feature. I am currently working on my own form library based around signals. The way I solved this transformation issue, is not by transforming the values onSubmit, but by handling the transformation on a per Field and onChange basis.

In my case, every field can have a transformToBinding function which takes the form value and transforms it for a specific input element (e.g. a number to a string) and a transformFromBinding function which does the opposite (e.g. transform a string to a number) There is also a special handleChangeBound function (transforms the value before setting it in the form) and transformedValue attribute (the form value just run through the transformer function) that both make use of these transformers.

The benefit of this is, that the typing would be a lot easier, since the FormValues would stay the same and only a per Field type has to change (also that type could then be inferred from the transformer functions). The second benefit is, that the form always holds the "correct" data at every point in time.

Maybe that might be something worth considering implementing here as well.

gutentag2012 avatar Jun 05 '24 22:06 gutentag2012

Hey @crutchcorn is this issue still up to date? If so, I think I can try to implement a small part of it.

t-rosa avatar Aug 07 '24 18:08 t-rosa