yeller.js - auto submit form with turbo stream

Edit
stimulus
Rails

JS version


make sure you pin

pin "@rails/request.js"


stimulus

//app/javascript/controllers/yeller_controller.js
import { Controller } from "@hotwired/stimulus"
import { FetchRequest } from "@rails/request.js"

export default class extends Controller {
  static values = { url: String, method: String }

  async call() {
    let form = this.element.querySelector('form')

    const formData = new FormData(form);
    formData.delete('_method')

    let url = this.hasUrlValue ? this.urlValue : form.action;
    let httpMethod = this.hasMethodValue ? this.methodValue : form.method;

    const request = new FetchRequest(httpMethod, url, {responseKind: "turbo-stream", body: formData})
    request.perform()
  }
}

use


to autosubmit to same endpoint where <form> points to (with same HTTP method)
div data-controller="yeller"
  = simple_form_for @model, url: some_path do |f|
    = f.input :whatever, as: :radio_buttons, input_html: { data: { action: "change->yeller#call" } }

to autosubmit form to different controller than where form points to (with same HTTP method)
div data-controller="yeller" data-yeller-url-value="#{different_path}" data-yeller-method-value="post"
  = simple_form_for @model, url: some_path do |f|
    = f.input :whatever, as: :radio_buttons, input_html: { data: { action: "change->yeller#call" } }



rails controller

def create
  @cq_form.update(cq_property_params)

  respond_to do |format|
    format.turbo_stream
  end
end