For some reason, I can’t get my head around this:
- Rails form, linked to a stimulus controller
- Button on the form has an action that points to a stimulus function, with a :prevent
<%= f.button 'Save Preferences', class: 'btn btn-action', data: {'service--autopay-target': 'save', action: 'service--autopay#formSubmit:prevent'} %>
I want to be able to call that formSubmit function to do some work before the form is submitted. After that work succeeds, I’m then submitting the form to the backend with:
this.formTarget.requestSubmit()
This works fine if you click the button, but doesn’t work if you press enter on the form - it skips the formSubmit() function in stimulus and just submits to Rails. If I move the action to the form, then the formSubmit function gets called twice, once on the enter key, and then again when the formTarget.requestSubmit() is called.
I have to be doing something wrong, but I can’t get my head around it. Does someone have an example of a stimulus bound form that can handle a “presubmit” like I’m trying to do?