hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.73k stars 428 forks source link

GET form data cannot be altered inside turbo:submit-start event #700

Open npezza93 opened 2 years ago

npezza93 commented 2 years ago

In the handbook(https://turbo.hotwired.dev/handbook/drive#form-submissions) it shows disabling form inputs inside the submit-start event. However if the form uses GET and the field(s) are disabled inside that event, those fields are still sent back to the server.

To get around this you have to hook into the before-fetch-request event with:

  beforeFetchRequest(e) {
    e.preventDefault()

    for(const input of e.target.elements) {
      input.disabled = true
    }

    const searchParams = new URLSearchParams()

    for (const [name, value] of new FormData(e.target).entries()) {
      if (value instanceof File) continue

      searchParams.append(name, value)
    }

    e.detail.url.search = searchParams.toString()

    e.detail.resume()
  }

This solution basically calls mergeFormDataEntries from form_submission and resets the search params. While this works, it feels like a hack since I'm copying code from inside Turbo and it behaves differently other type of forms like POST or PATCH.

arashnd commented 1 year ago

Had same issue & this is the workaround that I end up with

async beforeFetch(event) {
  event.preventDefault();

  this.element.querySelectorAll('[data-behaviour="readonly"]').forEach((input) => {
    event.detail.fetchOptions.body.delete(input.name)
    // fetchOptions.body is instance of URLSearchParams
  });

  event.detail.resume();
}
AbdullahAlForman commented 1 year ago

A