Home > Enterprise >  Best approach to override Bootstrap modal's close function in Rails 7.0.2.3 application with Bo
Best approach to override Bootstrap modal's close function in Rails 7.0.2.3 application with Bo

Time:09-05

I'm looking for the best approach to override the Bootstrap modal javascript close function. I have modal that pops up with a form that changes items on the page. The form doesn't close the modal when it is submitted. It stays on the form to allow users to create/delete as many tags as they like, rendering a turbo_stream.update partial instead of leaving the modal.

The issue is that once a user closes the modal after making their changes, the tag data on the page is stale and doesn't reflect the changes they made with the form displayed in the modal.

I'd like the bootstrap modal close function to either reload the page, or better yet render another turbo_stream.update partial to correct the tag information.

Calling the modal/form in view:

<%= link_to add_to_deck_tag_path, class: link_class, data: { turbo_frame: 'remote_modal' } do %><i ></i>Add Tag<% end %>

Remote modal code:

<%= turbo_frame_tag "remote_modal" do %>
  <div  id=modalLive" tabindex="-1" data-controller="remote_modal">
    <div >
      <div >
        <div >
          <h5  id="modalLiveLabel"><%= title %></h5>
          <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div id="remote_modal_body" >
          <%= yield %>
        </div>
      </div>
    </div>
  </div>
<% end %>

The javascript controller:

import { Controller } from "@hotwired/stimulus"
import { Modal } from "bootstrap"

export default class extends Controller {
  connect() {
    this.modal = new Modal(this.element)
    this.modal.show()
  }
}

CodePudding user response:

Ok, so this works to reload the page. I wasn't putting the addEventListener in the right place plus a few syntax issues.

I'm still working on rendering just the turbo-stream.update partial to avoid reloading the whole page.

import { Controller } from "@hotwired/stimulus"
import { Modal } from "bootstrap"

export default class extends Controller {
  connect() {
    this.modal = new Modal(this.element)
    this.modal.show()
    this.element.addEventListener('hidden.bs.modal', (event) => {
      location.reload();
      
    })
  }
}
  • Related