Skip to content

Latest commit

 

History

History
64 lines (50 loc) · 1.63 KB

submit-form.md

File metadata and controls

64 lines (50 loc) · 1.63 KB
title parent
Submit a Form Programmatically
With rails-ujs

Submit a Form Programmatically

by @julianrubisch {% avatar julianrubisch size=24 %}

{: .fs-3 }

<div controller="remote-form">
  <%= form_with(model: @article, html: { data: { action: "ajax:success->remote-form#onPostSuccess" } }) do |f| %>
    <%= select_tag "author", options_from_collection_for_select(@people, "id", "name"),
                   data: { action: "change->remote-form#update" } %>
  <% end %>
</div>

Won't Work {: .label .label-red }

import { Controller } from "stimulus";

export default class extends Controller {
  onPostSuccess(event) {
    console.log("success!");
  }

  update() {
    this.element.submit();
  }
}

{: .border-red}

Works {: .label .label-green}

import Rails from "@rails/ujs";
import { Controller } from "stimulus";

export default class extends Controller {
  onPostSuccess(event) {
    console.log("success!");
  }

  update() {
    Rails.fire(this.element, 'submit');
  }
}

{: .border-green}

Explanation

Rails-ujs intercepts form submit events that have a data-remote="true" attribute on the form element, but in the case of the HTMLFormElement.submit() method called, no event is even fired.

Reference