I have
- 1: a link in a turbo frame which loads a form into the same frame. Working Well
- 2: the form if it is not valid then should only update itself by marking the missing fields with errrors. Working Well
- 3: in case the form submission is successfull, I should redirect, that is not working well, because it is rendering the result of the redirect in
as TURBO_STREAM, somehow I should break out to top in that case.
Basically this is the code:
- list_of_projects...
= turbo_frame_tag 'new_project'
= link_to "New Project", new_project_path
then in views/projects/new.html.slim I have:
= turbo_frame_tag 'new_project' do
= simple_form_for @project_form, url: projects_path do |form|
...
Then in the controller:
def create
@project_form = ProjectForm.new project_params
if @project_form.valid?
command_bus.(Conversations::Commands::CreateProject.new(id: SecureRandom.uuid,
title: @project_form.title))
# should redirect without AS Turbo
redirect_to projects_url
Any ideas how to do it in a reusable manner?
A little foreword. If you just need to get out of the frame see other answers, or read the docs:
data-turbo-frameattribute is what you need. This answer is when you want to conditionally get out of the frame based on what happens during form submission.This is "new" in Turbo v7.3.0 (turbo-rails v1.4.0), redirect behavior when frame is missing is reverted to the original way of forever staying in a frame.
There is a
turbo:frame-missingevent emitted so that you could customize this behavior:Like this:
While this works, it does one more request to the server, which is what used to happen way back.
If you want to just display the redirected response, you can
visittheresponse:Turbo frame requests used to render without a layout, they now render within a tiny layout.
responsehas to be a full page response to be visitable, otherwise, turbo will refresh the page, which makes it even worse. This would fix it:Custom turbo stream redirect solution:
https://stackoverflow.com/a/75750578/207090
I think it's simpler than the solution below.
Set a custom header
This lets you choose on the front end if and when you want to break out of the frame.
Set a data attribute with a controller action name, like
data-missing="controller_action"(or any other trigger you need, like, controller name as well):This was more of a "i wonder if that would work" type of a solution, just make sure you need it:
https://turbo.hotwired.dev/handbook/frames#breaking-out-from-a-frame
https://github.com/hotwired/turbo/pull/863