title | parent |
---|---|
Submit a Form Programmatically |
With rails-ujs |
{: .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}
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.