Skip to content
全部文档

创建操作

简介

Filament 包含一个用于创建 Eloquent 记录的操作。点击触发按钮后,会打开带表单的模态框。用户填写表单后,数据会经过验证并保存到数据库。你可以这样使用:

php
use Filament\Actions\CreateAction;
use Filament\Forms\Components\TextInput;

CreateAction::make()
    ->schema([
        TextInput::make('title')
            ->required()
            ->maxLength(255),
        // ...
    ])
创建操作模态框创建操作模态框

保存前自定义数据

有时,你可能希望在最终保存到数据库之前修改表单数据。为此,可使用 mutateDataUsing() 方法;该方法可访问作为数组的 $data,并返回修改后的版本:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->mutateDataUsing(function (array $data): array {
        $data['user_id'] = auth()->id();

        return $data;
    })

TIP

除了 $data 之外,mutateDataUsing() 函数还可以注入各种实用工具作为参数。

自定义创建过程

你可以使用 using() 方法调整记录的创建方式:

php
use Filament\Actions\CreateAction;
use Illuminate\Database\Eloquent\Model;

CreateAction::make()
    ->using(function (array $data, string $model): Model {
        return $model::create($data);
    })

$model 是模型的类名,但你也可以按需替换为自己硬编码的类。

TIP

除了 $data$model 之外,using() 函数还可以注入各种实用工具作为参数。

创建后重定向

你可以使用 successRedirectUrl() 方法在表单提交后设置自定义重定向:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->successRedirectUrl(route('posts.list'))

若要根据已创建的记录进行重定向,请使用 $record 参数:

php
use Filament\Actions\CreateAction;
use Illuminate\Database\Eloquent\Model;

CreateAction::make()
    ->successRedirectUrl(fn (Model $record): string => route('posts.edit', [
        'post' => $record,
    ]))

TIP

除了 $record 之外,successRedirectUrl() 函数还可以注入各种实用工具作为参数。

自定义保存通知

记录成功创建后,会向用户发送通知,提示操作成功。

若要自定义该通知的标题,请使用 successNotificationTitle() 方法:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->successNotificationTitle('User registered')

TIP

除了允许静态值外,successNotificationTitle() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。

你可以使用 successNotification() 方法自定义整个通知:

php
use Filament\Actions\CreateAction;
use Filament\Notifications\Notification;

CreateAction::make()
    ->successNotification(
       Notification::make()
            ->success()
            ->title('User registered')
            ->body('The user has been created successfully.'),
    )

TIP

除了允许静态值外,successNotification() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。

若要完全禁用通知,请使用 successNotification(null) 方法:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->successNotification(null)

生命周期钩子

可以使用钩子在操作生命周期的不同节点执行代码,例如在表单保存之前。

可用钩子如下:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->beforeFormFilled(function () {
        // Runs before the form fields are populated with their default values.
    })
    ->afterFormFilled(function () {
        // Runs after the form fields are populated with their default values.
    })
    ->beforeFormValidated(function () {
        // Runs before the form fields are validated when the form is submitted.
    })
    ->afterFormValidated(function () {
        // Runs after the form fields are validated when the form is submitted.
    })
    ->before(function () {
        // Runs before the form fields are saved to the database.
    })
    ->after(function () {
        // Runs after the form fields are saved to the database.
    })

TIP

这些钩子函数可以注入各种实用工具作为参数。

中止创建过程

你可以随时在生命周期钩子或变更方法中调用 $action->halt(),这将中止整个创建过程:

php
use App\Models\Post;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Notifications\Notification;

CreateAction::make()
    ->before(function (CreateAction $action, Post $record) {
        if (! $record->team->subscribed()) {
            Notification::make()
                ->warning()
                ->title('You don\'t have an active subscription!')
                ->body('Choose a plan to continue.')
                ->persistent()
                ->actions([
                    Action::make('subscribe')
                        ->button()
                        ->url(route('subscribe'), shouldOpenInNewTab: true),
                ])
                ->send();
        
            $action->halt();
        }
    })

若还希望关闭操作模态框,可以改用 cancel() 完全取消操作,而不是仅中止:

php
$action->cancel();

使用向导

你可以轻松地将创建过程转换为多步向导。不要使用 schema(),而是定义 steps() 数组并传入你的 Step 对象:

php
use Filament\Actions\CreateAction;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Wizard\Step;

CreateAction::make()
    ->steps([
        Step::make('Name')
            ->description('Give the category a unique name')
            ->schema([
                TextInput::make('name')
                    ->required()
                    ->live()
                    ->afterStateUpdated(fn ($state, callable $set) => $set('slug', Str::slug($state))),
                TextInput::make('slug')
                    ->disabled()
                    ->required()
                    ->unique(Category::class, 'slug'),
            ])
            ->columns(2),
        Step::make('Description')
            ->description('Add some extra details')
            ->schema([
                MarkdownEditor::make('description'),
            ]),
        Step::make('Visibility')
            ->description('Control who can view it')
            ->schema([
                Toggle::make('is_visible')
                    ->label('Visible to customers.')
                    ->default(true),
            ]),
    ])

现在创建一条新记录,即可看到向导效果!编辑仍会使用资源类中定义的表单。

若希望允许自由导航、使所有步骤均可跳过,请使用 skippableSteps() 方法:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->steps([
        // ...
    ])
    ->skippableSteps()

继续创建另一条记录

修改「再创建一条」操作

若要修改「再创建一条」操作,可使用 createAnotherAction() 方法,并传入一个返回操作的函数。自定义操作触发按钮 可用的全部方法均可使用:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->createAnotherAction(fn (Action $action): Action => $action->label('Custom create another label'))

禁用「再创建一条」

若要从模态框中移除「再创建一条」按钮,可使用 createAnother(false) 方法:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->createAnother(false)

TIP

除了允许静态值外,createAnother() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。

再创建时保留数据

默认情况下,用户使用「创建并再创建一条」功能时,所有表单数据都会清空以便重新填写。若希望保留表单中的部分数据,可使用 preserveFormDataWhenCreatingAnother() 方法,并传入要保留的字段数组:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->preserveFormDataWhenCreatingAnother(['is_admin', 'organization'])

或者,你可以定义一个函数,返回要保留的 $data 数组:

php
use Filament\Actions\CreateAction;
use Illuminate\Support\Arr;

CreateAction::make()
    ->preserveFormDataWhenCreatingAnother(fn (array $data): array => Arr::only($data, ['is_admin', 'organization']))

若要保留全部数据,直接返回整个 $data 数组:

php
use Filament\Actions\CreateAction;

CreateAction::make()
    ->preserveFormDataWhenCreatingAnother(fn (array $data): array => $data)

TIP

除了允许静态值外,preserveFormDataWhenCreatingAnother() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。