teslamotors / informed

A lightweight framework and utility for building powerful forms in React applications
https://teslamotors.github.io/informed
MIT License
956 stars 174 forks source link

Q: Form with several buttons #442

Open grimgoon opened 1 year ago

grimgoon commented 1 year ago

Hey! I've been struggling with the following question:

const submit = ({values}) => {
  const isPublic = ?????
  await uploadBlog({ title: values.title, isPublic})
}

<Form onSubmit=(submit)>
    <TextField field="title" />
   <Button type='submit'>Save Draft</Button>
   <Button type='submit'>Create Blog</Button>
</Form>

In several cases when it comes to forms, I want to submit a form with slight alterations. Ergo, as in the example above:

I've been racking my brain trying to figure out the cleanest way to perform this... e.g with some type of onClick event on the buttons causing a state change / some hidden input.

But, I feel like there should be a way cleaner and more straightforward way to go about this. Does anyone have any thoughts?

Cheers!

joepuzzo commented 1 year ago

hmm I would suggest making the buttons type="button" then calling two different fuctions depending on the button.

i.e

saveDraft = () => {} vscreateBlog = () => {}

then inside of those I would call formApiRef.submitForm() and at this point your actual onSubmit can be called where you set some sort of flag based on function called

OR

you could NOT use two submit buttons and instead have a switch toggle input that says "Save As Draft" and be true or false.

grimgoon commented 1 year ago

That makes sense, thanks, @joepuzzo!

Potentially, an idea could maybe be to allow you to pass an optional object to the submitForm() function in the future.

That would allow you to pass in custom data, and the submit function would then give you the formState as the first argument as normal, and your (optional) object as the second.

formApiRef.submitForm({isPublic: true})