MarkC
MarkC

Reputation: 121

Bootstrap 5 follow link URL with Modal toggle

I'm trying to get a Modal with Bootstrap 5 to open the modal from a link, and then dynamically load the content (body of the modal) by sending the request onto the server which will then return the content (remote_modal_content) to be magically loaded into the now-visible Modal body.

I'm doing this using Rails 7 / Turboframes.

My link:


<a data-turbo-frame="remote_modal_content" data-bs-toggle="modal" data-bs-target="#remote_modal_frame" class="btn btn-outline-primary" href="/lists/3/issue_items/new">+</a>

The remote_modal_frame to be opened:

<div class="modal fade" id="remote_modal_frame" 
    tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">

        <%= turbo_frame_tag "remote_modal_content" %>

    </div>
</div>

The click on the link opens the Modal but the request to the href never gets sent to the server, and so magic never happens (the modal content is not populated).

I was doing something similar to this using Bootstrap 4 (with javascript rather than turbo) so this appears to be new behaviour in Bootstrap 5.

I'd be glad of any help someone could provide me.

Thanks, Mark

Upvotes: 1

Views: 1228

Answers (2)

GTO
GTO

Reputation: 479

If you don't want to use Stimulus, you can load your data with Turbo and then simulate click on special hidden link to open the modal.

  • The original functionality will stay the same: Turbo will load the content from show.html.erb and paste it to the turbo_frame inside modal.
  • The JS code catches the real click and simulates clicking on the hidden element to open the modal.

It's a workaround solution, but it's simple and it works.

<%= turbo_frame_tag item do %>
  <%= link_to "details", item_path(item), data: { turbo_frame: "item-frame" } %>
<% end %>

<div class="modal fade" id="itemModal" tabindex="-1" aria-labelledby="itemModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="itemModalLabel">item</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <%= turbo_frame_tag "item-frame" %>
    </div>
  </div>
</div>

<%= link_to "Show Modal", '#', data: { bs_toggle: "modal", bs_target: "#itemModal" }, id: "show-item-modal-id", class: "d-none" %>

<script>
  document.addEventListener("click", function (event) {
    if (event.target.getAttribute("data-turbo-frame") === "item-frame") {
      document.querySelector('#show-item-modal-id').click();
    }
  });
</script>

And in show.html.erb:

<%= turbo_frame_tag "item-frame" do %>
  <%# item content %>
<% end %>

Upvotes: 1

MarkC
MarkC

Reputation: 121

I resolved this on the hotwired community forum: https://discuss.hotwired.dev/t/dynamically-load-content-into-bootstrap-modal-using-turbo-stimulus/4607/2

Upvotes: 1

Related Questions