Premise
Modal dialogs have been haunting me (and I’m sure countless others) since I started developing for the web in 2004. Since the <dialog>
element has become supported in all major modern browsers, a lot of the boilerplate has been standardized (e.g. by providing a dialog
form method to capture and provide return values). Turbo’s idiosyncrasies, however, necessitate us to take a closer look at how to handle forms inside <dialog>
s.
Starting Point
I literally copied the “favorite animals” example from the MDN docs as a starting point. Clicking on “Update favorite animal” opens a dialog with a select box and a submit button. Selecting a new favorite animal works fine, but if you leave the select box empty, the dialog closes without showing any error:
Challenge
First of all, the Stackblitz backend mimicks exactly the way a Turbo powered Rails app would respond to a form action:
https://stackblitz.com/edit/turbo-frames-modals-validation?file=index.js%3AL28
- if valid, respond with a 303 pointing to the redirect location
- if invalid, respond with a 422 and include the error messages in the response.
Now, use a Turbo Frame to wrap the form and capture the validation errors:
https://stackblitz.com/edit/turbo-frames-modals-validation?file=index.html%3AL42
Caveats
Just wrapping the form with a Turbo Frame will yield another issue, this time with the valid response. You’ll need to add some custom JavaScript to handle it.