To create bulk actions, you must specify a method and a button title in the $bulkActions component property.
public array $bulkActions = [
'exportSelected' => 'Export',
];
The following method is only available in v1.16 and above
As of v1.16 you can define bulk action with a method, so you can perform other actions to determine what your actions are or perform translations on the strings:
public function bulkActions(): array
{
// Figure out what actions the admin gets
...
return [
'activate' => __('Activate'),
'deactivate' => __('Deactivate'),
];
}
The key is the Livewire method to call, and the value is the name of the item in the bulk actions dropdown.
You can define your method to do whatever you want:
public function exportSelected()
{
// Do something with the selected rows.
}
See Getting the selected rows query or Getting the selected keys to understand how to work with the selected data.
In the component, you have access to $this->selectedRowsQuery which is a Builder instance of the selected rows.
public function exportSelected()
{
if ($this->selectedRowsQuery->count() > 0) {
// Do something with the selected rows
}
// Notify there is nothing to export
}
If your bulk action is changing the outcome of your table, i.e. you are deleting rows or changing criteria that would alter the row set with the search criteria you have, then you may have unexpected results after the bulk action runs.
There is no one good way to handle this, so there are a few options available to you:
You can reset all the filters, search, page, sorts, etc. With this method, that will essentially reload the table to what it was on the first page load with your bulk changes since the query will re-run:
public function deleteSelected()
{
// Delete the rows
$this->resetAll();
}
You may at the end of your bulk action method reset specific parts of the UI with any of the following methods:
public function myBulkAction()
{
// Do something with the rows
// Use any of these to reset the UI to a point that makes sense after your bulk action is run:
$this->resetFilters(); // Remove all the filters
$this->resetSearch(); // Remove the search query
$this->resetSorts(); // Remove the sorts
$this->resetBulk(); // Clear the selected rows
$this->resetPage($this->pageName()); // Go back to page 1
}