复选框列表
概述
复选框列表(CheckboxList)组件允许你从预定义选项列表中选择多个值:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
'tailwind' => 'Tailwind CSS',
'alpine' => 'Alpine.js',
'laravel' => 'Laravel',
'livewire' => 'Laravel Livewire',
])

这些选项以 JSON 格式返回。如果你使用 Eloquent 保存数据,你应该添加 array casts 到对应的模型属性上:
use Illuminate\Database\Eloquent\Model;
class App extends Model
{
protected $casts = [
'technologies' => 'array',
];
// ...
}
设置选项描述
使用 descriptions() 方法,你可以选择为每个选项提供描 述。该方法接收一个普通文本字符串,或者 Illuminate\Support\HtmlString 和 Illuminate\Contracts\Support\Htmlable 实例。这就允许你在描述中渲染 HTML 甚至 Markdown 文本:
use Filament\Forms\Components\CheckboxList;
use Illuminate\Support\HtmlString;
CheckboxList::make('technologies')
->options([
'tailwind' => 'Tailwind CSS',
'alpine' => 'Alpine.js',
'laravel' => 'Laravel',
'livewire' => 'Laravel Livewire',
])
->descriptions([
'tailwind' => 'A utility-first CSS framework for rapidly building modern websites without ever leaving your HTML.',
'alpine' => new HtmlString('A rugged, minimal tool for composing behavior <strong>directly in your markup</strong>.'),
'laravel' => str('A **web application** framework with expressive, elegant syntax.')->inlineMarkdown()->toHtmlString(),
'livewire' => 'A full-stack framework for Laravel building dynamic interfaces simple, without leaving the comfort of Laravel.',
])

请确保在描述中使用与选项数组相同的 key,这样描述才能与选项匹配。
将选项拆分成多列
使用 columns() 方法,你可以将选项拆分成多列:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
// ...
])
->columns(2)

该方法接收和网格的 columns() 方法相同的选项。这就允许你在不同的临界点中响应式地自定义列数。
设置网格方向
默认情况下,列中的复选框列表按垂直方向排列。如果你想将其进行水平排列,你可以使用 gridDirection('row') 方法:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
// ...
])
->columns(2)
->gridDirection('row')

禁用特定选项
使用 disableOptionWhen() 方法,可以禁用特定选项。它接受一个闭包,在闭包中你可以检测选项是否是特定要被禁用的 $value 值:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
'tailwind' => 'Tailwind CSS',
'alpine' => 'Alpine.js',
'laravel' => 'Laravel',
'livewire' => 'Laravel Livewire',
])
->disableOptionWhen(fn (string $value): bool => $value === 'livewire')
如果你想检索选项是否未被禁用,比如,为了验证数据,你可以使用 getEnabledOptions():
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
'tailwind' => 'Tailwind CSS',
'alpine' => 'Alpine.js',
'laravel' => 'Laravel',
'livewire' => 'Laravel Livewire',
'heroicons' => 'SVG icons',
])
->disableOptionWhen(fn (string $value): bool => $value === 'heroicons')
->in(fn (CheckboxList $component): array => array_keys($component->getEnabledOptions()))
搜索选项
使用 searchable() 方法,你可以启用搜索框,以快速访问选项:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
// ...
])
->searchable()

批 量切换复选框
使用 bulkToggleable() 方法,你可以允许用户一次性切换所有复选框:
use Filament\Forms\Components\CheckboxList;
CheckboxList::make('technologies')
->options([
// ...
])
->bulkToggleable()






