FilamentF
Filament3y ago
4 replies
daan5964

Modal File Upload for Widget Buttons

I'm developing a board with multiple widgets, including tables. One widget links to a resource where users can upload files and metadata on a new page. I'm exploring the possibility of creating a button that opens a modal for the same purpose within the widget. While the button exists, it's uncertain if it can be linked to an action that opens a modal.
Solution
To create an Action that opens a modal with a file upload field, you can do something like this:


Actions\Action::make('upload')
    ->label('Upload a document')
    ->form([
        Hidden::make('name'),
        Hidden::make('mime'),

        FileUpload::make('path')
            ->directory('uploads')
            ->visibility('public')
            ->getUploadedFileNameForStorageUsing(
                fn(TemporaryUploadedFile $file) => sprintf('file_%s.%s', Str::random(), $file->getClientOriginalExtension())
            )
            ->afterStateUpdated(function ($state, Set $set) {
                if ($state instanceof TemporaryUploadedFile) {
                    $set('name', $state->getClientOriginalName());
                    $set('mime', $state->getMimeType());
                }
            })
            ->columnSpanFull(),
    ])
    ->modalSubmitActionLabel('Create')
    ->action(function ($data) {

        $document = Document::create([
            'user_id' => Auth::id(),
            'path' => $data['path'],
            'mime' => $data['mime'],
            'name' => $data['name'],
        ]);

        // do whatever 
    });
Was this page helpful?