So i tried to use Sweetalert to show delete confirmation modal and I’m using Livewire powergrid to show the list of my data.
The problem is. If I’m navigating to the List components. The Javascript, that i pushed in the list components are not working.
But if i refresh the page in the list componets. It works again.
I’ve tried to use wire:navigated on the javascript add event listeners. It’s still not working
I’ve tried to add data-navigate-once in my script tag. It’s still not working.
So, down here is how it works.
The data generated using powergrid in the data I’m adding row action button
<?php
#[On('client-deleted')]
public function clientDeleted($clientId) {}
public function actions(AppModelsClient $row): array
{
return [
// Edit Button
Button::add('delete')
->slot('Delete')
->id()
->class('btn btn-danger')
->dispatchTo('clients.list-client', 'trigger-delete-client', ['client' => $row])
];
}
If we click the button it will trigger an event in my list-client component, as You can see the script section.
<div>
<x-page-header pageName="Client" />
<x-partials.flash />
<div class="row">
<div class="col-12">
<div class="card shadow-lg mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h4 class="m-0 font-weight-bold text-primary">List Client</h4>
<a href={{ route('client.create') }} class="btn btn-primary" wire:navigate>
<i class="bi bi-person-plus-fill"></i>
<span>Client</span>
</a>
</div>
<div class="card-body">
<livewire:tables.client-table />
</div>
</div>
</div>
</div>
</div>
@push('scripts')
<script type="text/javascript" data-navigate-once>
document.addEventListener('livewire:navigated', function () {
@this.on('trigger-delete-client', client => {
Swal.fire({
title: 'Are You Sure?',
text: 'Conatct record will be deleted!',
icon: "warning",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#aaa',
confirmButtonText: 'Delete!'
}).then((result) => {
//if user clicks on delete
if (result.value) {
// calling destroy method to delete
@this.call('destroy', client)
// success response
Swal.fire({title: 'Contact deleted successfully!', icon: 'success'});
} else {
Swal.fire({
title: 'Operation Cancelled!',
icon: 'success'
});
}
});
});
})
</script>
@endpush
And it will show a modal confirmation box. If we click Yes/Confirm it will run this code. which will delete the data and reload it. For the reload part, you can scroll back to the Table component above where I’m defining it right before i create a delete button.
<?php
class ListClient extends Component
{
public function render()
{
return view('livewire.clients.list-client');
}
public function destroy(AppModelsClient $client)
{
try {
DB::beginTransaction();
$client->delete();
DB::commit();
} catch (Throwable $th) {
DB::rollBack();
Log::error($th);
}
$this->dispatch('client-deleted', $client->id)->to(ClientTable::class);
}
}
I’ve followed this tutorial, but maybe because my lack of knowledge, It’s not working.