Injector controller: pattern for modals

For those reading this now, this problem can now be simply solved with turbo-frames from the turbo-rails gem and a little bit of stimulus js.

This approach seems to work well for me:

# some view
<%= turbo_frame_tag "new_group" do %>
   <%= link_to "New group", new_group_path  %>
<% end %>

  # groups/new.html.erb
  <%= turbo_frame_tag "new_group" do %>
    <div data-controller="modal">
         <----- insert the modal stuff here ----->
    </div>    

         <-------- If the modal is cancelled you still may want to access the form again ----->
          <%= link_to "New group", new_group__path%>
  <% end %>

We can initialise the modal with a simple stimulus js controller:

// modal_controller.js
import { Controller } from "stimulus";

export default class extends Controller {
  connect(){       
    $(this.element).modal();
  }

  disconnect() {    
	$(this.element).modal('hide');	  // hide if we cancel
  }
}

In my case I’m using bootstrap with jQuery - so obviously you’ll want to handle that.

This allows for a complex work flow - i can create a new group within another form while still being on the same page.

I might have missed something - apologies if i have. hope this helps.

1 Like