Skip to content

Tổng quan ​

Lớp FileAction kế thừa Filament\Actions\Action, tạo ra một action Filament tuỳ chỉnh cho phép người dùng tải lên, quản lý và xoá tệp đính kèm gắn với một model. Action này đặc biệt hữu ích cho các hệ thống trò chuyện hoặc quản lý nhiệm vụ, nơi người dùng cần đính kèm tệp vào tin nhắn, nhiệm vụ hoặc các đối tượng khác.

Các tính năng chính của FileAction ​

  1. Tải tệp lên

    • Hỗ trợ tải lên nhiều tệp.
    • Tệp được lưu trong thư mục chats-attachments.
    • Người dùng có thể xem trước, tải xuống, sắp xếp lại và xoá tệp.
  2. Giới hạn loại tệp

    • Chỉ chấp nhận một số loại tệp như ảnh, PDF, tài liệu Word, bảng tính Excel và tệp văn bản thuần.
    • Kích thước tệp tối đa 10 MB (10.240 KB).
  3. Thông báo

    • Thông báo thành công khi tải lên hoặc xoá tệp.
    • Thông báo cảnh báo nếu không có tệp mới để tải lên.
    • Thông báo lỗi khi có sự cố.
  4. Tích hợp cơ sở dữ liệu

    • Dùng quan hệ attachments để lấy các tệp đính kèm hiện có.
    • Chặn tải trùng tệp bằng cách kiểm tra các tệp đã tải lên.
    • Khi gỡ tệp, xoá cả trong cơ sở dữ liệu lẫn nơi lưu trữ.
  5. Tuỳ chỉnh giao diện Filament

    • Dùng cửa sổ modal để quản lý tệp.
    • Có nhãn đếm hiển thị số tệp đính kèm hiện có.
    • Dùng nút viền màu xám kèm chú thích (tooltip) để trải nghiệm tốt hơn.

Phân tích cách cài đặt FileAction ​

Định nghĩa tên action ​

php
public static function getDefaultName(): ?string
{
    return 'file.action';
}
  • Đặt tên action duy nhất (file.action) để tham chiếu khi dùng action này trong các resource của Filament.

Thiết lập action ​

Phương thức setUp() cấu hình cách action này hoạt động.

php
protected function setUp(): void
{
    parent::setUp();

    // Rest of code
}
  • Gọi phương thức setUp() của lớp cha để đảm bảo phần thiết lập action mặc định của Filament được chạy.

Tuỳ chỉnh giao diện ​

php
$this
    ->color('gray')
    ->outlined()
    ->tooltip(__('chatter::filament/resources/actions/chatter/file-action.setup.tooltip'))
  • Nút action có màu xám và dạng viền để trông nhẹ nhàng.
  • Chú thích (tooltip) giải thích thêm action này làm gì.

Hiển thị số tệp đính kèm ​

php
->badge(fn ($record) => $record->attachments()->count())
  • Hiển thị nhãn đếm trên nút action, cho biết số tệp đính kèm.

Thành phần tải tệp lên ​

Biểu mẫu chứa thành phần FileUpload:

php
->form([
    Forms\Components\FileUpload::make('files')
        ->hiddenLabel()
        ->multiple()
        ->directory('chats-attachments')
        ->downloadable()
        ->openable()
        ->reorderable()
        ->previewable(true)
        ->deletable()
  • Cho phép tải lên nhiều tệp.
  • Lưu tệp trong thư mục chats-attachments.
  • Người dùng có thể tải xuống, xem trước, sắp xếp lại và xoá tệp.

Kiểm tra tệp ​

php
->acceptedFileTypes([
    'image/*',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/plain',
])
->maxSize(10240) // 10 MB
  • Chỉ cho phép ảnh, PDF, Word, Excel và tệp văn bản.
  • Giới hạn kích thước 10 MB mỗi tệp.

Xoá tệp đã tải lên ​

php
->deleteUploadedFileUsing(function ($file, ?Model $record) {
    $attachment = $record->attachments()
        ->where('file_path', $file)
        ->first();

    if ($attachment) {
        $attachment->delete();

        Notification::make()
            ->success()
            ->title(__('chatter::filament/resources/actions/chatter/file-action.setup.form.fields.actions.delete.title'))
            ->body(__('chatter::filament/resources/actions/chatter/file-action.setup.form.fields.actions.delete.body'))
            ->send();
    }
})
  • Tìm tệp đính kèm trong cơ sở dữ liệu và xoá khi người dùng yêu cầu.
  • Gửi thông báo thành công khi xoá xong.

Đặt danh sách tệp mặc định (tệp tải sẵn) ​

php
->default(function (?Model $record) {
    if (! $record) {
        return [];
    }

    return $record->attachments()
        ->latest()
        ->get()
        ->pluck('file_path')
        ->toArray() ?? [];
}),
  • Tải sẵn đường dẫn tệp hiện có khi mở action.

Xử lý action (tải tệp lên model) ​

php
->action(function (FileAction $action, array $data, ?Model $record): void {
    try {
        $existingFiles = $record->attachments()
            ->latest()
            ->get()
            ->pluck('file_path')
            ->toArray();

        $newFiles = array_filter($data['files'] ?? [], function ($file) use ($existingFiles) {
            return ! in_array($file, $existingFiles);
        });

        if (! empty($newFiles)) {
            $record->addAttachments($newFiles);

            Notification::make()
                ->success()
                ->title(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.success.title'))
                ->body(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.success.body'))
                ->send();
        } else {
            Notification::make()
                ->info()
                ->title(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.warning.title'))
                ->body(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.warning.body'))
                ->send();
        }
    } catch (\Exception $e) {
        Notification::make()
            ->danger()
            ->title(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.error.title'))
            ->body(__('chatter::filament/resources/actions/chatter/file-action.setup.actions.notification.error.body'))
            ->send();

        report($e);
    }

    $action->resetFormData();
})
  • Lọc bỏ tệp trùng (không tải lại các tệp đã có).
  • Gọi $record->addAttachments($newFiles) để gắn tệp mới vào model.
  • Gửi thông báo thành công, cảnh báo hoặc lỗi tuỳ theo kết quả.
  • Xử lý ngoại lệ để tránh bị dừng đột ngột.
php
->modalHeading(__('chatter::filament/resources/actions/chatter/file-action.setup.title'))
->icon('heroicon-o-paper-clip')
->modalIcon('heroicon-o-paper-clip')
->iconPosition(IconPosition::Before)
->modalSubmitAction(
    fn ($action) => $action
        ->label('Upload')
        ->icon('heroicon-m-paper-airplane')
)
->modalWidth(MaxWidth::ThreeExtraLarge)
->slideOver(false);

Nội dung dựa trên AureusERP User Guide của Webkul (giấy phép MIT), Việt hoá và biên tập bởi Softway.