Pass Model to re-useable Table Action
I've got a delete action which is repeated in various places.
I want write the component in a helper class and then call it into the
getTableActions
array as required.
To do this, I need to pass the model, but I can't make it work, it is passing a closure.
Tried lots of iterations like this:
Solution:Jump to solution
The handler is separate.
I've worked it out!
I was overcomplicating this...I thought I'd have to pass the $record into
deleteApplication
function so it can return the Action::make('deleteApplication')
...8 Replies
Dont' declare the Model and just pass in $record.
Thanks for reply.
I tried that previously.
The return of the $record is not even being got to. It gets to the
deleteApplication
function before the closure is processed. I don't get to see the 'here' dd.That isn't making much sense. Sure;y you want:
TableAction::deleteApplication('deleteApp')->action(function ($record) {
dd('here', $record);
return $record;
})
Hmmm...maybe I've misunderstood what I can do. Here is the
deleteApplication
function (cut down):
Which is a trait of the class TableAction
.
As this table delete action is appearing in various places, I am trying to avoid rewriting it for every location.So you build your own trait function.... Sorry catching up now.
You are supposed to pass the model/record in so calling the closure within the function wouldn't work I wouldn't think.... You just need to pass in the record and till the record what to do.
What are you trying to achieve?
I'm using this delete action in various places and resources, so I don't want to have it written out in full on each occasion. By the time you've done the tooltip, the modal description etc, its chunky.
So I'm trying pass the $record to the trait function, to be utilised in the returned Action.
What are you running in the action? because surely that should be part of the model and you just call 'delete()' on the record?
Solution
The handler is separate.
I've worked it out!
I was overcomplicating this...I thought I'd have to pass the $record into
deleteApplication
function so it can return the Action::make('deleteApplication')
Which makes sense, until you think about for longer than 5 minutes. The $record attribute is being injected in the Action::make()
function, and therefore it is fine just to leave $record in the normal places, so the trait looks like:
`''trait Application
{
public static function deleteApplication() : Action
{
return Action::make('deleteApplication')
->label('')
->visible(function ($record) {
return $record->canBeDeleted();
})
->requiresConfirmation()
->action(function (DeleteApplicationHandler $handler, $record) {
$handler->handle($record);
});
}
}'''
In conclusion, the answer to the question how to "Pass Model to re-useable Table Action" is....you don't need to there, it is already available.
Apologies for wasting your time !