表单构造器 - 字段
Radio
概述
Radio 提供了一组单选按钮,用以从一组预定义选项中选择一个值:
use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published' ])
![Radio](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/simple.jpg?raw=true)
设置选项描述
使用 descriptions()
方法,你可以为每个选项提供描述说明:
use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published' ]) ->descriptions([ 'draft' => 'Is not visible.', 'scheduled' => 'Will be visible.', 'published' => 'Is visible.' ])
![Radio with option descriptions](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/option-descriptions.jpg?raw=true)
请确保在描述数组中与选项数组中使用的 key
是相同的,这样描述与选项才能匹配正确。
布尔值选项
你可以使用 boolean()
方法,来表示简单的布尔值,如"是"和"否"选项:
Radio::make('feedback') ->label('Like this post?') ->boolean()
![Boolean radio](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/boolean.jpg?raw=true)
将选项显示在标签行内
如果你希望将选项在标签行内(inline()
)显示,而非显示在标签之下:
Radio::make('feedback') ->label('Like this post?') ->boolean() ->inline()
![Inline radio](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/inline.jpg?raw=true)
将选项在标签之下行内显示
如果你想将选项在标签之下行内显示,请使用 inline()
方法:
Radio::make('feedback') ->label('Like this post?') ->boolean() ->inline() ->inlineLabel(false)
![Inline radio under label](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/inline-under-label.jpg?raw=true)
禁用指定选项
使用 disableOptionWhen()
方法,可以禁用指定的选项。它接收一个闭包,在该闭包中你可以检查选项是否为该禁用的指定 $value
:
use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published', ]) ->disableOptionWhen(fn (string $value): bool => $value === 'published')
![Radio with disabled option](https://github.com/filamentphp/filament/blob/3.x/docs-assets/screenshots/images/light/forms/fields/radio/disabled-option.jpg?raw=true)
如果你想检索未被禁用的选项,比如,用于验证数据,你可以使用 getEnabledOptions()
:
use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published', ]) ->disableOptionWhen(fn (string $value): bool => $value === 'published') ->in(fn (Radio $component): array => array_keys($component->getEnabledOptions()))
Edit on GitHubStill need help? Join our Discord community or open a GitHub discussion