Rails/Stimulus: What is the best way to get form field values when handling form submission with Stimulus?

Viewed 204

I have a form but Stimulus will handle its submission.

<%= form_with model: @booking, data: { controller: 'booking', action: 'booking#submitForm:prevent' } do |form| %>
  <%= form.text_field :name, data: { 'booking-target' => 'name' } %>
  <%= form.text_field :pet_name, data: { 'booking-target' => 'pet' } %>

  <%= form.submit "Submit form" %>
<% end %>
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  
  static targets = ['name', 'pet']

  submitForm() {
    console.log('Submitting form')
    console.log('Name: ' + this.nameTarget.value)
    console.log('Pet: ' + this.petTarget.value)
  }
}

The above code works but I have specified the target name for each field in the form. This isn't a problem with a small form but would be cumbersome if the form had many more fields. Is there a more elegant way to expose the field data?

1 Answers

You don't have to specify targets and just use the form directly:

submitForm(e) {
  // get it directly from the form
  console.log(e.target.name, e.target.name.value)        

  // or like this
  console.log(e.target["pet_name"], e.target["pet_name"].value)

  // get everything
  const data = Object.fromEntries(new FormData(e.target).entries())
  console.log(data)
}

BTW, you can also do this:

# <%= form.text_field :name, data: { 'booking-target' => 'name' } %>
<%= form.text_field :name, data: { booking_target: :name } %>
Related