fabian-hiller / modular-forms

The modular and type-safe form library for SolidJS, Qwik and Preact
https://modularforms.dev
MIT License
932 stars 45 forks source link

Modularize the Form onSubmit method #216

Open danielrkling opened 1 week ago

danielrkling commented 1 week ago

Summary

I think it would be useful to separate out the onSubmit logic inside the Form component into it's own method. However, it seems like this library is planned on being rewritten soon so maybe this is just something to think about for that.

Motivation:

Using multiple submit type actions seems more complicated then needed Current Options (Maybe there are better ways)

  1. Attach values to the submitter button/input and read those values in the onSubmit event handler.
  2. Rewrite the code in the onSubmit function.

Implentation

  1. Add a new method like handleSubmit(form,onSubmit,options?,event?)
  2. Method essentially is essentially the same except how to handle event object
  3. Call this method from the Form Component onSubmit event handler, and pass the event object

Example

<Form>
  <Field>...</Field>

  <button onclick={() =>
      handleSubmit(form, (values) => console.log(values), { ...options1 })
  }>
    Action 1
  </button>
  <button onclick={() =>
      handleSubmit(form, (values) => console.warn(values), { ...options2 })
  }>
    Action 2
  </button>
</Form>

Love the library and thanks for the work. I can work on a PR if needed (This would be my first time)

fabian-hiller commented 1 week ago

Is your motivation to execute different logic when a certain button is clicked?

danielrkling commented 1 week ago

Yes, different logic for each button but sharing the same form/data. For my particular case now it's different api endpoints for saving the data.

fabian-hiller commented 1 week ago

This is already possible. Just use a button with an event handler and check with validate if your form is valid.

<Form>
  <Field>...</Field>

  <button onclick={async () => {
      if (await validate(form)) {
        // ...
      }
  }}>
    Action 1
  </button>
  <button onclick={async () => {
      if (await validate(form)) {
        // ...
      }
  }}>
    Action 2
  </button>
</Form>
danielrkling commented 1 week ago

Right, but if I also want to update the submit states and response state, I am essentially rewriting the entire function that's in the Form onSubmit event. Granted, it's still not that much, but this sparked my idea to just pull it out to its own method.

fabian-hiller commented 1 week ago

Thanks for your feedback! I will consider it when rewriting the library at some point in the future.