Form with Stimulus and submit on enter key

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?

Never fails. I go around and around on something and then it magically works after I post my question to the internet. Sigh.

Here’s a slimmed down version of what worked for anyone who finds this later:

<%= form_with model: ..., url: ..., data: {'service--autopay-target': 'form', turbo_frame: "_top", action: 'service--autopay#formSubmit:prevent'} do |f| %>
   Form Fields here

   <%= f.submit 'Save Preferences', class: 'btn btn-action', data: {'service--autopay-target': 'save', turbo: false} %>
<% end %>

I think this is working because I removed the action from the button, moved it to the form, then changed the button to a submit with data-turbo = false.