Stimulus Controller for Bootstrap Modal
Stimulus controller
connect() {
this.modal = new bootstrap.Modal(this.element)
this.modal.show() (1)
}
1 | Auto-open modal on connect |
catch turbo-submit:end event
close modal after form submit
handleSubmit = (event) => {
if (event.detail.success) {
console.log("modal#handleSubmit successful")
// may be do some other stuff here ....;
}
// always close modal after form submit
this.close()
}
<1>
The complete controller
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
// auto-open modal on connect
connect() {
console.log("modal#connect")
this.modal = new bootstrap.Modal(this.element)
this.modal.show()
}
disconnect() {
console.log("modal#disconnect")
}
close() {
console.log("modal#close")
this.modal.hide()
}
// catch turbo:submit-end via action
handleSubmit = (event) => {
console.log("modal#handleSubmit")
// close modal if form submission is successful
if (event.detail.success) {
console.log("modal#handleSubmit event successful")
}
this.close()
}
}