Skip to main content

RemoteFormController

Purpose

A Stimulus controller to deal with Rails UJS remote forms and their submission responses.

Acts like LoadBlockController in that it will receive an HTML partial in response to a UJS remote-form submission that it can hot-swap into the DOM, but using UJS as a vehicle instead of a GET fetch request.

Actions

ActionPurpose
replaceReplace the attached form with the contents of the response. Needs to be wired up to the UJS ajax:success and/or ajax:error events.

Targets

TargetPurposeDefault
---

Classes

ClassPurposeDefault
---

Values

ValueTypeDescriptionDefault
selector (Optional)StringA css selector to query the response with. The selected element(s) are what the attached form will be replaced with.The controller identifier. It looks for another form with the same controller in the response

Events

EventWhenDispatched onevent.detail
remote-form:replaceAfter the form has been replaced with the responseThe new form element-

Side Effects

None

How to Use

Annotate a Rails form with data-remote: true and add this controller. You can then send HTML responses from the server that this controller will pick up and replace the connected form element with.

When listening for remote-form:replace, it's worth noting that because the <form> element is replaced, any event listeners you attach to it will be lost. So make sure to either listen on document or an ancestor of the <form> element.

HTML / ERB

<%= simple_form_for model, method: :post, remote: true, data: { controller: 'remote-form', action: 'ajax:success->remote-form#replace ajax:error->remote-form#replace' } do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<% end %>