Well, here’s the semi-quick version:
I originally built an alert display that works by listening for a sendalert event, and then expanded on it to send a callback event.
Here’s the component:
class Confirmationdisplay extends Component
{
public $confirmations = [];
public $listeners = [
'sendConfirmation' => 'receiveConfirmation'
];
public function receiveConfirmation($message, $callback, $callbackData = null)
{
$confirmation = [
'message' => $message,
'callback' => $callback,
'callbackData' => $callbackData
];
array_push($this->confirmations, $confirmation);
}
public function confirm($key)
{
$this->emit($this->confirmations[$key]['callback'], $this->confirmations[$key]['callbackData']);
$this->removeConfirmation($key);
}
public function removeConfirmation($key)
{
unset($this->confirmations[$key]);
}
public function render()
{
return view('livewire.confirmationdisplay');
}
}
For the view, design it how you want, the main points are:
You will need the key from the confimations array in your view:
@foreach($this->confirmations as $key => $confirmation)
Put the key into your binding for the confirm/accept:
<a href wire:click.prevent="confirm({{$key}})">Confirm</a>
And for the cancel/close:
wire:click="removeConfirmation({{$key}})"
From your “requesting” component, you only need a listener and two methods:
public $listeners = [
'deleteArtistCallback' => 'delete'
];
public function confirmDelete($id)
{
$artistName = SingleReturn::artistName($id);
$this->emit('sendConfirmation', "Delete Artist: $artistName?", 'deleteArtistCallback', $id);
}
public function delete($id)
{
$artist = Artist::find($id);
$artist->delete();
}
The confimDelete fires an event for the confirmation component to render with the parameters $message, $callback, $callbackData.
$callback is the event that is fired when confirm/accept is clicked, and what you are listening for in the requesting component. $callbackData is optional, and is whatever you need in your function; in most cases just the id.
If anyone is going to copy/paste this, just keep event name clashing and validation in mind. I stick my validation in my model with something along the lines of:
public function delete($user = null)
{
$user = $this->getUserForModel($user);
if ($user->is_admin) {
return parent::delete();
}
return false;
}
You could build the same concept with out the events into the original component, and css the alert where you want it. I made it separate because I use it in multiple areas of a project, so it’s very reusable.