If you have an Action in FilamentPHP and want to trigger another action sequentially within it, you can use the Action Chaining feature.
Example Scenario
Suppose you have an action called DuplicateAction
, and after it completes, you want the EditAction
to open automatically. Below is an example implementation of both actions.
EditAction Example
Here’s how you can define the EditAction
:
Action::make('edit')
->fillForm(function (array $arguments) {
$id = $arguments['id'];
$item = Item::find($id);
return $item ? $item->toArray() : [];
})
->form(fn () => [
// Your form fields go here
])
->action(function (array $arguments, $data) {
$id = $arguments['id'];
$item = Item::find($id);
if (!$item) {
return;
}
$item->update($data);
});
DuplicateAction Example
Here’s how you can define the DuplicateAction
and trigger the EditAction
after duplicating:
return Action::make('duplicate')
->requiresConfirmation()
->modalDescription('Are you sure you want to duplicate this item?')
->action(function (array $arguments) {
$id = $arguments['id'];
$isEdit = isset($arguments['edit']);
$item = Item::find($id);
if (!$item) {
return;
}
$newItem = $item->replicate();
$newItem->name = $newItem->name . ' (copy)';
$newItem->afterNode($item)->save();
if ($isEdit) {
$this->replaceMountedAction('edit', [
'id' => $newItem->id,
]);
}
})
->extraModalFooterActions(fn (Action $action): array => [
$action->makeModalSubmitAction('duplicateAndEdit', arguments: ['edit' => true])
->label('Duplicate and Edit'),
]);
Explanation
- EditAction: Opens a form pre-filled with the data of the selected item. When the user submits the form, it updates the item in the database.
-
DuplicateAction:
- Duplicates the selected item and appends " (copy)" to its name.
- Offers an additional button in the modal footer, labeled "Duplicate and Edit," which duplicates the item and directly triggers the
EditAction
with the duplicated item's data.
By using this method, you can seamlessly open actions sequentially, enhancing the user experience.
Top comments (0)