For my administration, i develop a new button Field to display on the index page of my userCrudController. When clicked, it should launch an ajax action. So to do this js logic, i create this stimulus controller.
import { Controller } from '@hotwired/stimulus';
import { Toast } from 'bootstrap';
import { createToast, createSpinner } from '../js/customs';
/*
* Ajax button Field Logic
*/
export default class extends Controller {
static targets = [];
sucessToast = null;
failedToast = null;
disable = false;
connect() {
// Search if Toast Element is already create on the page
// if not, we create it
let sucessToast = document.querySelector('#successAjaxToast');
if(!sucessToast) {
createToast('successAjaxToast', 'bg-success', 4000);
sucessToast = document.querySelector('#successAjaxToast');
}
let failedToast = document.querySelector('#failedAjaxToast');
if(!failedToast) {
createToast('failedAjaxToast', 'bg-danger', 4000);
failedToast = document.querySelector('#failedAjaxToast');
}
this.sucessToast = new Toast(sucessToast);
this.failedToast = new Toast(failedToast);
}
runAjax(event) {
let url = event.params.ajaxUrl;
let sucessToast = document.querySelector('#successAjaxToast');
let failedToast = document.querySelector('#failedAjaxToast');
let saveInnerHtml = event.target.innerHTML;
let dims = event.target.getBoundingClientRect();
if (!this.disable) {
this.disable = true;
event.target.innerHTML = createSpinner('').outerHTML;
event.target.style.width = dims.width + 'px';
fetch(url)
.then(obj => obj.json())
.then(data => {
if (data.error) {
throw data.errorMessage;
}
if (data.successMessage) {
sucessToast.querySelector('.toast-body').innerHTML = data.successMessage;
} else {
sucessToast.querySelector('.toast-body').innerHTML = 'Succès';
}
this.sucessToast.show();
})
.catch(e => {
failedToast.querySelector('.toast-body').innerHTML = e;
this.failedToast.show();
console.warn(e)
})
.finally(() => {
this.disable = false;
event.target.innerHTML = saveInnerHtml;
event.target.style.width = 'auto';
})
;
}
}
}
The problem is that I import Toast from bootstrap. And that makes me end up with two bootstraps loaded on my page. And so my dropdown action buttons, didn't open anymore when i click on '...' (because the action is launch twice)
I tried to override the index template in order to don't load easyadmin "app.js" It's work,bootstrap is load only once, but of course, this solution make me lost some js logic, like "click on delete" button who don't work anymore. So this is not a real good solution.
Somebody know how i could use bootstrap Toast in my stimulus controller without loading twice bootstrap js logic?
Thank for help :)