F
Filament11mo ago
scalar

How to save data to two models in createOptionForm of Select at the same time?

Hello everyone, hope you are doing well! There is a Client model and a Group model in the database. Client model: id, name Group model: id, name, client_id When creating a new client using createOptionForm, I want to create a new group based on client_id after creating a new client at the same time. The problem is how to get client_id and then save it to the Group model. This is the select tag:
Forms\Components\Section::make()
->schema([
Forms\Components\Select::make('client_id')
->relationship('client', 'name')
->label('Client')
->createOptionForm([
Forms\Components\Section::make('')
->schema([
Forms\Components\TextInput::make('name')
->label('Client Name')
->required()
->maxLength(255)
->columnSpan('full'),

Forms\Components\Section::make('group')
->schema([
Forms\Components\TextInput::make('name')
->label('Group Name')
->required()
->maxLength(255),
})
})
})
Forms\Components\Section::make()
->schema([
Forms\Components\Select::make('client_id')
->relationship('client', 'name')
->label('Client')
->createOptionForm([
Forms\Components\Section::make('')
->schema([
Forms\Components\TextInput::make('name')
->label('Client Name')
->required()
->maxLength(255)
->columnSpan('full'),

Forms\Components\Section::make('group')
->schema([
Forms\Components\TextInput::make('name')
->label('Group Name')
->required()
->maxLength(255),
})
})
})
Thank you!
2 Replies
ChesterS
ChesterS11mo ago
I believe you can override what happens when you save using createOptionUsing callback. Something like
->createOptionUsing(function(array $data, Select $component) {
... // do whatever you need here
})
->createOptionUsing(function(array $data, Select $component) {
... // do whatever you need here
})
You can have a look at the default action in vendor/filament/forms/src/Components/Select.php
$this->createOptionUsing(static function (Select $component, array $data, Form $form) {
$record = $component->getRelationship()->getRelated();
$record->fill($data);
$record->save();

$form->model($record)->saveRelationships();

return $record->getKey();
});
$this->createOptionUsing(static function (Select $component, array $data, Form $form) {
$record = $component->getRelationship()->getRelated();
$record->fill($data);
$record->save();

$form->model($record)->saveRelationships();

return $record->getKey();
});
Don't know if there's another/better way
scalar
scalarOP11mo ago
Ok got it, thank you.
Want results from more Discord servers?
Add your server