Filament实现仅创建时显示密码输入框的报错及解决问询
解决Filament中密码字段仅在创建时显示的问题
错误原因
你遇到的Target [Filament\Pages\Page] is not instantiable错误,是因为Filament\Pages\Page是抽象类,无法通过Laravel服务容器实例化,所以不能直接在闭包中依赖注入该类。
正确实现方式
有两种简洁的方式实现密码字段仅在创建记录时显示:
方法1:通过$context判断操作场景
Filament会自动为表单闭包注入$context变量,值为create(创建)或edit(更新),直接用它判断即可:
use Filament\Forms\Components\TextInput; TextInput::make('password') ->password() // 标记为密码输入框,隐藏输入内容 ->required() ->visible(fn (string $context): bool => $context === 'create');
方法2:通过getLivewire()获取当前组件实例
如果在非Resource的表单场景(比如独立页面表单),可以用getLivewire()函数获取当前Livewire组件实例,判断是否属于CreateRecord页面:
use Filament\Resources\Pages\CreateRecord; use Filament\Forms\Components\TextInput; TextInput::make('password') ->password() ->required(fn () => getLivewire() instanceof CreateRecord) ->visible(fn () => getLivewire() instanceof CreateRecord);
两种方法都能实现你的需求:创建记录时显示并要求必填密码,更新记录时隐藏该字段。
内容的提问来源于stack exchange,提问作者tolga
相关产品推荐
相关产品推荐

