author avatar

nitturu.baba

Mon Sep 30 2024

The default behavior of a form's submit button in Rails is to disable itself once the form has been submitted. In any situation if you want to submit form multiple times without reloading the page, we can use a simple trick:

  1. Move the submit button outside of the form.
  2. Create a controller that connects the button and the form.
  3. Implement an action in controller to submit the form when the button is clicked. Form:
<%= form_with(model: @object, data: {
    controller: "form",
    form_target: "form"
}) do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>

  <%= form.label :status %>
  <%= form.select :status, ["Active", "Inactive"] %>

<% end %>

<%= button_tag "submit", type: "submit", data: {
      action: "click->form#formSubmit"
    } %>

Controller:

export default class extends Controller {
    static targets = ["form"];

    formSubmit(){
        this.formTarget.submit()
    }
}

Why This Works By placing the button outside the form, it becomes unlinked from the form submission process, allowing it to remain enabled even after the form is submitted.

<#CU6U0R822|> #form #stimulus