1

I have a form which creates a new post, and a stimulus controller that clears the input fields after submission. However, it does this before the input values reach my rails controller.

This is my form_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  clear() {
    this.element.reset()
  }
}

my form:

<turbo-frame id='<%= id %>'>
  <%= form_with model: post, data: { controller: :form } do |f| %>
    Title: <%= f.text_field :title %>
    Body: <%= f.text_area :body %>
    <%= f.submit data: {action: 'form#clear'} %>
<% end %>
</turbo-frame>

Everything works great, except that an empty post gets created (I have no validations) because my input fields are wiped clean by the Js before they reach my Rails controller.

I did look around and found this post but don't really know what to do. How to clear a text area after an "ajax" form request with ruby on rails

def avi
  • 506
  • 6
  • 10

1 Answers1

2

The event is being executed on submit button click instead try running it on form submit. Didn't test the code but you might want to do something like this:

Try 1:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  connect() {
    this.element.addEventListener("submit", clear);
  }

  clear() {
    this.element.reset()
  }
}

And remove the action from submit button:

<%= f.submit %>

Or you can try this (running the action on turbo submit):

Try 2:

<turbo-frame id='<%= id %>'>
  <%= form_with model: post, data: { controller: :form, action: "turbo:submit-end->form#clear" } do |f| %>
    Title: <%= f.text_field :title %>
    Body: <%= f.text_area :body %>
    <%= f.submit %>
  <% end %>
</turbo-frame>
Deepesh
  • 6,138
  • 1
  • 24
  • 41
  • 1
    yup the second snippet works. I also found a discussion thread on the hotwire forum that addresses the same issue. https://discuss.hotwired.dev/t/resetting-form-after-turbo-streams-submission/3615 – def avi Mar 15 '22 at 02:40
  • I have the same use-case as OP and the second solution worked perfectly. Thank you. – Jordan F Nov 15 '22 at 14:46