F
Filament15mo ago
Sesh

How to stop an action on certain conditions with ->before()

What is the best practice in Filament to stop an action from continuing before it runs into a exception? For example I want to show a message to the user if delete is not possible because the category is used for items:
DeleteAction::make('delete')
->before(function (TrendRadarTrendSegment $record) {
if ($record->radarTrends()->count() > 0) {
Notification::make()
->title('Delete failed')
->body(__('This segment is used by trends and cannot be deleted. Please move the trends to another segment first.'))
->danger()
->send();
}
})
DeleteAction::make('delete')
->before(function (TrendRadarTrendSegment $record) {
if ($record->radarTrends()->count() > 0) {
Notification::make()
->title('Delete failed')
->body(__('This segment is used by trends and cannot be deleted. Please move the trends to another segment first.'))
->danger()
->send();
}
})
How can I break out of the DeleteAction in this case? Or is there another way to catch en exception and show a notification?
3 Replies
Yurii
Yurii14mo ago
@Sascha did you find a better way to handle exceptions from actions? Currently, I have similar question. Your approach would work, however, it's only presentation level condition/restriction and I am wondering if it is possible to throw an exception on a model level (if any action is not allowed) and handle it correctly here.
@uwascan
@uwascan14mo ago
you may use halt() / $this->halt(). It depends on your context (page or static). you may google more about it
Yurii
Yurii14mo ago
I am using Detach action on RelationManager. However, on a model level I am restricting the ability to detach for some cases. If I throw an exception from the model and it just displays the expection page. My expectation was that it would show the exception message as a failure notification but I cannot find how to configure it in the way.
Want results from more Discord servers?
Add your server