Hi,
I’m trying to figure out how to use Turbo to present a form in a modal.
For the sake of this example let’s say the model is a Group.
In the application.html.erb
layout I’ve added the following line before the closing body tag:
<%= turbo_frame_tag "modal" %>
To present the modal, the user clicks the following link in index.html.erb
:
<%= link_to 'Create new', new_group_path, data: { 'turbo-frame': 'modal' } %>
The new.html.erb
view looks like this:
<%= turbo_frame_tag "modal" do %>
<%= form_with model: @group, url: groups_path, local: true, data: { 'turbo-frame': '_top' } do |form| %>
<%= form.submit _('Create') %>
<% end %>
<% end %>
Finally, the relevant actions in GroupsController look like this:
def new
@group = Group.new
end
def create
@group = Group.new(group_params)
respond_to do |format|
if @group.save
format.html { redirect_to group_path(@group) }
else
format.html { render :new, status: :unprocessable_entity }
end
end
end
This almost works. When the link is clicked, the form is fetched and inserted into the corresponding <turbo_frame id=“modal”> (I then use a Stimulus controller to present it).
When the form submission is successful, Turbo will navigate from /groups
to /groups/1
.
However, if a validation error occurs, Turbo will remain on /groups
but the entire page is replaced with the contents of new.html.erb
. This is because of the data: { 'turbo-frame': '_top' }
attribute on the form.
If I remove it, the redirect on a successful form submission does not work.
Is there a best practice for handling this?