概述
简介

表单字段类在 Filament\Form\Components
命名空间之下。它们位于组件的 schema 数组中。Filament 自带多种类型的字段,适用于编辑不同类型的数据:
- Text input
- Select
- Checkbox
- Toggle
- Checkbox list
- Radio
- 日期时间选择器
- 文件上传
- 富文本编辑器
- Markdown 编辑器
- Repeater
- Builder
- Tags input
- Textarea
- Key-value
- 颜色选择器
- Toggle 按钮
- Slider
- 代码编辑器
- Hidden
你也可以创建自定义字段,以按照你希望的方式编辑数据。、
字 段可以通过静态的 make()
方法创建,并传递其唯一名称。通常,字段名称与 Eloquent 模型上的属性名称相对应:
use Filament\Forms\Components\TextInput;
TextInput::make('name')

你可以使用“点语法”将字段绑定到数组中的键:
use Filament\Forms\Components\TextInput;
TextInput::make('socials.github_url')
验证字段
在 Laravel 中,验证规则通常定义在像 ['required','max:255']
这样的数组中, 或者像 required|max:255
这样的组合字符串中。如果你只在后端处理简单的表单请求,这很好。但 Filament 也能够为你的用户提供前端验证,这样他们就可以在发出任何后端请求之前修复错误。
在 Filament 中,你可以使用 required()
和 maxLength()
等方法向字段添加验证规则。这也优于 Laravel 的验证语法,因为你的 IDE 可以自动 补全这些方法:
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Section;
TextInput::make('name')
->required()
->maxLength(255)
在此示例中,该字段是 required()
的且有一个 maxLength()
验证。大部分 Laravel 的验证规则都可以以方法的方式调用,你甚至可以添加自己的自定义规则。
设置字段标签
默认情况下,字段的标签将基于字段名称自动生成。要重写字段标签,请使用 label()
方法:
use Filament\Forms\Components\TextInput;
TextInput::make('name')
->label('Full name')
除了允许静态值之外,label()
方法也接受一个函数来动态计算其值。你可以将多个 utility 作为参数注入到该函数中。
Learn more about utility injection.Utility | Type | Parameter | Description |
---|---|---|---|
Field | Filament\Forms\Components\Field | $component | The current field component instance. |
Get function | Filament\Schemas\Components\Utilities\Get | $get | A function for retrieving values from the current form data. Validation is not run. |
Livewire | Livewire\Component | $livewire | The Livewire component instance. |
Eloquent model FQN | ?string<Illuminate\Database\Eloquent\Model> | $model | The Eloquent model FQN for the current schema. |
Operation | string | $operation | The current operation being performed by the schema. Usually <code>create</code>, <code>edit</code>, or <code>view</code>. |
Raw state | mixed | $rawState | The current value of the field, before state casts were applied. Validation is not run. |
Eloquent record | ?Illuminate\Database\Eloquent\Model | $record | The Eloquent record for the current schema. |
State | mixed | $state | The current value of the field. Validation is not run. |
如果你需要为本地化使用翻译字符串,那么以此方式自定义标签非常有用:
use Filament\Forms\Components\TextInput;
TextInput::make('name')
->label(__('fields.name'))
TIP
你也可以使用 JavaScript 表达式来确定标签的内容,它可以读取表单中字段的当前值、