Can afterStateHydrated know if new record or editing?

When using the afterStateHydrated on a select field in a form, can you know if it's in the modal for creating a new record or updating an existing one? I only want to set the pre-selected value of parent_id when creating a new record through the 'simple' resource manager but not when editing an existing record so the value of an existing records parent_id doesn't accidentally change.
Forms\Components\Select::make( 'parent_id' )
->options( self::getSelectParentChoices() )
->afterStateHydrated( static function ( Forms\Components\Select $component, $state, callable $get ) {
//TODO Don't do this when editing an exisitng record
$viewingParentId = $component->getLivewire()->parent_id ?? - 1;
$component->state($viewingParentId);
} )
Forms\Components\Select::make( 'parent_id' )
->options( self::getSelectParentChoices() )
->afterStateHydrated( static function ( Forms\Components\Select $component, $state, callable $get ) {
//TODO Don't do this when editing an exisitng record
$viewingParentId = $component->getLivewire()->parent_id ?? - 1;
$component->state($viewingParentId);
} )
3 Replies
awcodes
awcodes2y ago
$context should be available as an argument. then you can check:
if ($context === 'create') {
... do stuff
}
if ($context === 'create') {
... do stuff
}
LeandroFerreira
or default
->default(function ($livewire, $component, $state, $get) {
return ...
})
->default(function ($livewire, $component, $state, $get) {
return ...
})
jelmerkeij
jelmerkeijOP2y ago
Thanks, I now see this is described in the Advanced Forms documentation! https://filamentphp.com/docs/2.x/forms/advanced
Filament
Advanced - Form Builder - Filament
The elegant TALL stack form builder for Laravel artisans.
Want results from more Discord servers?
Add your server