新建记录
保存前自定义数据
有时,你可能希望在表单数据最终保存到数据库之前对其进行修改。为此,你可以在新建页面类中定义一个 mutateFormDataBeforeCreate()
方法,该方法接受 $data
作为数组,并返回修改后的版本:
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['user_id'] = auth()->id();
return $data;
}
或者,如果你在模态操作中创建记录,请查看操作文档。
自定义创建过程
你可以使用新建页面类中的 handleRecordCreation()
方法来调整记录的创建方式:
use Illuminate\Database\Eloquent\Model;
protected function handleRecordCreation(array $data): Model
{
return static::getModel()::create($data);
}
此外,如果你在模态框 Action 中创建记录,请查看 Action 文档
自定义重定向
默认情况下,在保存表单之后,用户将会重定向到对应资源的编辑页面,或者在视图页面存在的情况下,重定向到[视图页面】(viewing-records)
通过重写新建页面类的 getRedirectUrl()
方法,你可以自定义表单保存后的重定向路径。
比如,表单可以重定向到列表页:
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('index');
}
如果你想重定向到之前的页面,否则重定向到 index 页面:
protected function getRedirectUrl(): string
{
return $this->previousUrl ?? $this->getResource()::getUrl('index');
}
你可以使用配置来一次性为所有资源定义默认重定向页面:
use Filament\Panel;
public function panel(Panel $panel): Panel
{
return $panel
// ...
->resourceCreatePageRedirect('index') // or
->resourceCreatePageRedirect('view') // or
->resourceCreatePageRedirect('edit');
}
自定义保存通知
记录创建成功时,通知会发送给用户,说明用户操作成功。
要自定义通知的标题,请在新建页面类中定义 getCreatedNotificationTitle()
方法:
protected function getCreatedNotificationTitle(): ?string
{
return 'User registered';
}