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
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>