FilamentPHP关联选择字段创建新记录报错,需设置createOptionUsing
问题解决:FilamentPHP Select字段创建关联模型错误
错误原因
你仅配置了创建地址的表单结构createOptionForm(),但Filament无法自动处理关联模型的保存逻辑——新创建的地址需要关联到当前选中的Relation实例,因此必须通过createOptionUsing()闭包明确定义如何保存新地址并返回其ID。
修改后的表单代码
public static function form(Form $form): Form { return $form ->schema([ Forms\Components\Select::make('relation_id') ->label('Kies een relatie') ->required() ->options(Relation::all()->pluck('contact_name', 'id')) ->reactive(), Forms\Components\Select::make('relation_address_id') ->label('Kies een adres') ->options(function(callable $get){ $relation = Relation::find($get('relation_id')); return $relation ? $relation->addresses()->pluck('name', 'id') : []; }) ->hidden(fn (Closure $get) => is_null($get('relation_id'))) ->createOptionForm([ Forms\Components\TextInput::make('name')->label('Naam') ->required() ->maxLength(255), Forms\Components\TextInput::make('postalcode')->label('Postcode') ->required() ->maxLength(255), Forms\Components\TextInput::make('housenumber')->label('Huisnummer') ->required() ->maxLength(255), Forms\Components\TextInput::make('street')->label('Straat') ->required() ->maxLength(255), Forms\Components\TextInput::make('city')->label('Stad') ->required() ->maxLength(255), Forms\Components\Select::make('country_id')->label('Land') ->options(Country::where('enabled', 1)->pluck('name', 'id')) ->required(), ]) // 新增:定义创建选项的保存逻辑 ->createOptionUsing(function (array $data, callable $get) { $relationId = $get('relation_id'); if (!$relationId) { throw new \Exception('Geen relatie geselecteerd'); } // 创建并关联新地址 $address = RelationAddress::create([ ...$data, 'relation_id' => $relationId, // 关联到当前选中的Relation ]); // 返回新地址的ID,供Select字段选中 return $address->id; }), ]); }
关键修改说明
createOptionUsing()闭包:- 接收表单提交的
$data(新地址的字段值)和$get函数(用于获取当前表单的relation_id) - 将
relation_id注入到新地址的创建数据中,确保地址关联到正确的Relation - 返回新地址的ID,让Select字段自动选中这个新创建的选项
- 接收表单提交的
补充验证:
- 给
country_id添加了->required(),确保必填字段完整 - 简化了
options方法的判断逻辑,保持代码简洁
- 给
内容的提问来源于stack exchange,提问作者Piet Hendri
相关产品推荐
相关产品推荐

