You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Filament中formatStateUsing()影响同名TextInput字段的解决方法

同名TextInput字段的formatStateUsing()方法互相干扰的解决办法

我有两个TextInput字段,都命名为ref_no:其中一个使用了formatStateUsing()方法提取状态值中-之前的前缀,另一个未使用该方法,但前者的格式化逻辑同时影响了后者的显示,请问该如何避免这种情况?

原代码:

TextInput::make('ref_no')
        ->label('Reference No.')
        ->reactive()
        ->disabled()
        ->formatStateUsing(fn ($state) => Str::before($state, '-'))
        ->columnSpan(1),

TextInput::make('ref_no')
        ->label('Reference No.')
        ->columnSpan(2),

解决方案:
通过afterStateHydrated()方法替代formatStateUsing()来处理第一个字段的前缀提取,同时将未修改的原始ref_no值赋值给新的字段step_two_ref_no,让第二个字段绑定到这个新字段上,避免同名导致的状态共享干扰。

解决后的代码:

TextInput::make('ref_no')
                ->label('Reference No.')
                ->reactive()
                ->disabled()
                ->afterStateHydrated(function ($component, $state, $set) {
                    $prefix = Str::before($state, '-');
                    $component->state($prefix);
                    $set('step_two_ref_no', $state); 
                })
                ->columnSpan(1),

 TextInput::make('step_two_ref_no')
                    ->label('Reference No.')
                    ->columnSpan(2),

内容的提问来源于stack exchange,提问作者Nelson Castro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:54:53