FilamentF
Filamentโ€ข2y ago
nowak

How to trigger a custom action modal directly from a TextInputColumn updateStateUsing?

I have a TextInputColumn on a table for my resources
route_id
attribute. When this is changed to a
route_id
that does not exist, I want to prompt the user with an action modal, where they can create a new
route
record, which would update the
route_id
column with the id of the newly created route.
I am trying to do this:
TextInputColumn::make('route_id')
  ->rules(['numeric', 'integer', 'min:1'])
  ->extraAttributes(['style' => 'min-width:60px'])
  ->updateStateUsing(function ($state, $record) {
    if ($state > 1 || $state !== null) {
        $route = Route::find($state);

        if (!$route) {
          // Trigger the createRoute action if the route does not exist
          return Action::make('createRoute')
            ->form([
              TextInput::make('name')->required()->maxLength(255),
              ColorPicker::make('color')->required(),
            ])
            ->action(function (array $data) use ($state) {
              $data['id'] = $state;
              Route::create($data);
            })
            ->modalHeading('Create Route')
            ->modalSubmitActionLabel('Create')
            ->modalWidth('lg')
            ->visible(fn () => true);
      }
      $groupOrderUpdater = app(UpdatesGroupOrders::class);
      $groupOrderUpdater->update($record, ['route_id' => $state]);
    }
    return $record->route_id;
  }),


But the action modal does not get triggered at all, what am I doing wrong?
Solution
We cannot register an Action here, I guess. I created a header action as a workaround. Is it elegant? No, but it might work for your case.

ListPage
protected function getHeaderActions(): array
{
    return [
        Actions\Action::make('createRoute')
            ->form([
                TextInput::make('name')->required()->maxLength(255),
                ColorPicker::make('color')->required(),
            ])
            ->action(function (array $arguments, array $data) {
                $data['id'] = $arguments['id'];
                Route::create($data);
            })
            ->modalHeading('Create Route')
            ->modalSubmitActionLabel('Create')
            ->modalWidth('lg')
            ->extraAttributes(['class' => 'hidden'])
    ];
}


TextInputColumn::make('route_id')
->updateStateUsing(function (Page $livewire, $state, Model $record) {
    if ($state > 1 || $state !== null) {
        //...
        $livewire->mountAction('createRoute', ['id' => $state]);
    }
})
Was this page helpful?