Skip to content

Instantly share code, notes, and snippets.

@mithicher
Last active August 24, 2023 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mithicher/8399a5d2ddd4cc691b8eee751dacf06c to your computer and use it in GitHub Desktop.
Save mithicher/8399a5d2ddd4cc691b8eee751dacf06c to your computer and use it in GitHub Desktop.
SweetAlert2 Confirm Deletion
// Usage:
// <x-button type="button" wire:confirm="delete(1)">Confirm Test</x-button>
document.addEventListener('livewire:init', () => {
Livewire.directive('confirm', ({ el, directive, component, cleanup }) => {
let content = directive.expression
// This regex splits the method given: eg. "delete(1)" to ['delete(1)', 'delete', '1']
const regex = /([a-zA-Z_][a-zA-Z0-9_]*)\((['"][^'"]*['"]|\d+)\)/;
const matches = directive.expression.match(regex);
let onClick = e => {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#aaa',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
component.$wire.call(matches[1], matches[2])
}
});
}
el.addEventListener('click', onClick, { capture: true })
cleanup(() => {
el.removeEventListener('click', onClick)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment