Skip to content
全部文档

编辑记录

资源编辑页面资源编辑页面

填充表单前自定义数据

你可能希望在数据填入表单前修改记录数据。可在编辑页类上定义 mutateFormDataBeforeFill(),修改 $data 数组并返回修改后的版本,再填入表单:

php
protected function mutateFormDataBeforeFill(array $data): array
{
    $data['user_id'] = auth()->id();

    return $data;
}

或者,若在模态操作中编辑记录,请参阅 操作文档

保存前自定义数据

有时,你可能希望在数据最终写入数据库前修改表单数据。可在编辑页类上定义 mutateFormDataBeforeSave(),接收 $data 数组并返回修改后的版本:

php
protected function mutateFormDataBeforeSave(array $data): array
{
    $data['last_edited_by_id'] = auth()->id();

    return $data;
}

或者,若在模态操作中编辑记录,请参阅 操作文档

自定义保存过程

可用编辑页类上的 handleRecordUpdate() 方法调整记录的更新方式:

php
use Illuminate\Database\Eloquent\Model;

protected function handleRecordUpdate(Model $record, array $data): Model
{
    $record->update($data);

    return $record;
}

或者,若在模态操作中编辑记录,请参阅 操作文档

自定义重定向

默认情况下,保存表单不会将用户重定向到其他页面。

可通过覆盖编辑页类上的 getRedirectUrl(),在保存表单时设置自定义重定向。

例如,表单可重定向回资源的 列表页

php
protected function getRedirectUrl(): string
{
    return $this->getResource()::getUrl('index');
}

查看页

php
protected function getRedirectUrl(): string
{
    return $this->getResource()::getUrl('view', ['record' => $this->getRecord()]);
}

若希望重定向到上一页,否则到索引页:

php
protected function getRedirectUrl(): string
{
    return $this->previousUrl ?? $this->getResource()::getUrl('index');
}

也可使用 配置 一次性自定义所有资源的默认重定向页面:

php
use Filament\Panel;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->resourceEditPageRedirect('index') // or
        ->resourceEditPageRedirect('view');
}

自定义保存通知

记录成功更新后,会向用户派发通知,表明操作成功。

要自定义该通知的标题,在编辑页类上定义 getSavedNotificationTitle() 方法:

php
protected function getSavedNotificationTitle(): ?string
{
    return 'User updated';
}

或者,若在模态操作中编辑记录,请参阅 操作文档

可通过覆盖编辑页类上的 getSavedNotification() 自定义整个通知:

php
use Filament\Notifications\Notification;

protected function getSavedNotification(): ?Notification
{
    return Notification::make()
        ->success()
        ->title('User updated')
        ->body('The user has been saved successfully.');
}

要完全禁用通知,从编辑页类的 getSavedNotification() 返回 null

php
use Filament\Notifications\Notification;

protected function getSavedNotification(): ?Notification
{
    return null;
}

生命周期钩子

钩子可在页面生命周期的多个节点执行代码,例如在表单保存前。要设置钩子,在编辑页类上创建与钩子同名的 protected 方法:

php
protected function beforeSave(): void
{
    // ...
}

在此例中,beforeSave() 中的代码会在表单数据写入数据库之前调用。

编辑页有若干可用钩子:

php
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    // ...

    protected function beforeFill(): void
    {
        // Runs before the form fields are populated from the database.
    }

    protected function afterFill(): void
    {
        // Runs after the form fields are populated from the database.
    }

    protected function beforeValidate(): void
    {
        // Runs before the form fields are validated when the form is saved.
    }

    protected function afterValidate(): void
    {
        // Runs after the form fields are validated when the form is saved.
    }

    protected function beforeSave(): void
    {
        // Runs before the form fields are saved to the database.
    }

    protected function afterSave(): void
    {
        // Runs after the form fields are saved to the database.
    }
}

或者,若在模态操作中编辑记录,请参阅 操作文档

在 trait 中定义生命周期钩子

要在 trait 中定义生命周期钩子,请在钩子名后加上 trait 名称。这遵循 Eloquent 的 boot{TraitName}() 与 Livewire 的 mount{TraitName}() 约定,使可复用 trait 能接入页面生命周期,又不会与页面自身定义的钩子冲突:

php
use Filament\Resources\Pages\EditRecord;

trait HandlesDrafts
{
    protected function afterSaveHandlesDrafts(): void
    {
        // Runs after the form fields are saved to the database, in addition
        // to the hook on the page.
    }
}

class EditUser extends EditRecord
{
    use HandlesDrafts;

    protected function afterSave(): void
    {
        // Both lifecycle hooks are called.
    }
}

页面自身的钩子先调用,随后是各个 trait 钩子。其他 trait 所使用的 trait 中的钩子也会被调用。Trait 钩子会自动调用,因此不应再从页面自身的钩子中调用它们。

独立保存表单的一部分

你可能希望允许用户独立于表单其余部分保存其中一部分。一种做法是使用 页眉或页脚中的 section 操作。在 action() 方法中可调用 saveFormComponentOnly(),并传入要保存的 Section 组件:

php
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Schemas\Components\Section;

Section::make('Rate limiting')
    ->schema([
        // ...
    ])
    ->footerActions([
        fn (string $operation): Action => Action::make('save')
            ->action(function (Section $component, EditRecord $livewire) {
                $livewire->saveFormComponentOnly($component);
                
                Notification::make()
                    ->title('Rate limiting saved')
                    ->body('The rate limiting settings have been saved successfully.')
                    ->success()
                    ->send();
            })
            ->visible($operation === 'edit'),
    ])

可使用 $operation 辅助变量,确保该操作仅在编辑表单时可见。

带 section 页脚保存操作的资源编辑页面带 section 页脚保存操作的资源编辑页面

中止保存过程

可随时在生命周期钩子或变更方法中调用 $this->halt(),以中止整个保存过程:

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

protected function beforeSave(): void
{
    if (! $this->getRecord()->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();

        $this->halt();
    }
}

或者,若在模态操作中编辑记录,请参阅 操作文档

授权

对于授权,Filament 会遵循应用中已注册的任意 模型策略

若模型策略的 update() 方法返回 true,用户即可访问编辑页。

若策略的 delete() 方法返回 true,他们还可删除该记录。

自定义操作

「操作」是显示在页面上的按钮,允许用户运行页面上的 Livewire 方法或访问 URL。

在资源页面上,操作通常出现在两处:页面右上角,以及表单下方。

例如,可在编辑页的「Delete」旁添加新的按钮操作:

php
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    // ...

    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('impersonate')
                ->action(function (): void {
                    // ...
                }),
            Actions\DeleteAction::make(),
        ];
    }
}
带自定义页眉操作的资源编辑页面带自定义页眉操作的资源编辑页面

或者,在表单下方「Save」旁添加新按钮:

php
use Filament\Actions\Action;
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    // ...

    protected function getFormActions(): array
    {
        return [
            ...parent::getFormActions(),
            Action::make('close')->action('saveAndClose'),
        ];
    }

    public function saveAndClose(): void
    {
        // ...
    }
}

要查看完整的操作 API,请访问 页面部分

将保存操作按钮添加到页眉

可通过覆盖 getHeaderActions() 并使用 getSaveFormAction(),将「Save」按钮添加到页面页眉。需要向操作传入 formId(),指明应提交 ID 为 form 的表单,这是页面视图中使用的 <form> ID:

php
protected function getHeaderActions(): array
{
    return [
        $this->getSaveFormAction()
            ->formId('form'),
    ];
}

可通过覆盖 getFormActions() 返回空数组,移除表单上的所有操作:

php
protected function getFormActions(): array
{
    return [];
}
页眉含保存操作的资源编辑页面页眉含保存操作的资源编辑页面

创建另一个编辑页

单个编辑页可能不足以容纳大量表单字段。你可以为资源创建任意多个编辑页。若使用 资源子导航,在不同编辑页之间切换会特别方便。

要创建编辑页,应使用 make:filament-page 命令:

bash
php artisan make:filament-page EditCustomerContact --resource=CustomerResource --type=EditRecord

你必须在资源的 getPages() 方法中注册该新页面:

php
public static function getPages(): array
{
    return [
        'index' => Pages\ListCustomers::route('/'),
        'create' => Pages\CreateCustomer::route('/create'),
        'view' => Pages\ViewCustomer::route('/{record}'),
        'edit' => Pages\EditCustomer::route('/{record}/edit'),
        'edit-contact' => Pages\EditCustomerContact::route('/{record}/edit/contact'),
    ];
}

现在可为该页面定义 form(),其中可包含主编辑页上没有的其他字段:

php
use Filament\Schemas\Schema;

public function form(Schema $schema): Schema
{
    return $schema
        ->components([
            // ...
        ]);
}

将编辑页加入资源子导航

若使用 资源子导航,可在资源的 getRecordSubNavigation() 中照常注册该页面:

php
use App\Filament\Resources\Customers\Pages;
use Filament\Resources\Pages\Page;

public static function getRecordSubNavigation(Page $page): array
{
    return $page->generateNavigationItems([
        // ...
        Pages\EditCustomerContact::class,
    ]);
}

自定义页面内容

Filament 中每个页面都有自己的 schema,定义整体结构与内容。可通过定义 content() 方法覆盖页面 schema。编辑页的 content() 默认包含以下组件:

php
use Filament\Schemas\Schema;

public function content(Schema $schema): Schema
{
    return $schema
        ->components([
            $this->getFormContentComponent(), // This method returns a component to display the form that is defined in this resource
            $this->getRelationManagersContentComponent(), // This method returns a component to display the relation managers that are defined in this resource
        ]);
}

components() 数组中可插入任意 schema 组件。可通过调整数组顺序重排组件,或移除不需要的组件。

使用自定义 Blade 视图

若需进一步自定义,可将页面类上的静态 $view 属性覆盖为应用中的自定义视图:

php
protected string $view = 'filament.resources.users.pages.edit-user';

这假定你已在 resources/views/filament/resources/users/pages/edit-user.blade.php 创建了视图:

blade
<x-filament-panels::page>
    {{-- `$this->getRecord()` will return the current Eloquent record for this page --}}
    
    {{ $this->content }} {{-- This will render the content of the page defined in the `content()` method, which can be removed if you want to start from scratch --}}
</x-filament-panels::page>