Easiest way to remove turbo frame

Hi, I’v got the form which opens within turbo frame on clicking Add button. There are buttons Save and Cancel within the frame. What is the easiest way to just delete that turbo frame on Cancel ? I think I could do this with some stimulus controller and sending turbo stream or with extra url and rails controller action but maybe it’s possible with just pure html/turbo_streams ?

You could do some sort of dismiss stimulus controller that you can click and it removes the element.
Or you could do it from a turbo_stream response in the controller which could be helpful if you want to perform some additional actions before you remove the frame.

You don’t need any JS to make the request just change your button to a link and add a data-turbo-method attribute

`

Unless, cancelling triggers something server-side, I would use a stimulus controller to remove the frame.

If it was an edit with a save and cancel, then the cancel would revert back from the edit state to the show state (in which case, the frame would be replaced by show).

In case of an add, there is normally nothing to be fetched from the server, so a stimulus controller would be enough to just remove the frame.

Now that I am rereading this post you actually don’t need to do anything except make the link redirect to the page that initially shows the turbo-frame for the new form

Here’s an example

// posts/index.html.erb
<%= turbo_frame_tag :new_post, src: :new_posts_path %>

// posts/new.html.erb
<%= turbo_frame_tag :new_post do %>
  // form for the post
  <%= link_to "cancel", posts_path %>
<% end %>

clicking on the link to cancel would simply redirect to the index page and reset the frame to the initial state

1 Like

This works! I would have expected that it reloads and I end up on top of it. But it actually stays in the scroll position.

Any suggestions on how I would be able to make this reusable across my app? I have a turbo frame “modal” that I’d like to be able to have just a simple “cancel” button. I can use something like <%= link_to "cancel", posts_path %> but that only works if the modal was rendered on my posts controller. How would I make it reusable so I can call the modal anywhere and remove the same modal?

<%= link_to 'Cancel', :back %>
1 Like

I use a dedicated controller for clearing any frame on the page.

match 'turbo-frame/clear/:id',
  to:  'turbo_frames#clear',
  as:  :clear_turbo_frame,
  via: %i[get post]
# frozen_string_literal: true

# rubocop:disable Rails/ApplicationController, Rails/RenderInline
class TurboFramesController < AbstractApplicationController

  def clear
    render inline: '<%= turbo_frame_tag(params[:id]) %>'
  end

end
# rubocop:enable Rails/ApplicationController, Rails/RenderInline
button_to(clear_turbo_frame_path(id: :tfModal), method: :get)