#How can I fill a field on the edit form that isn't saved to the database?

1 messages · Page 1 of 1 (latest)

normal cobalt
#

On a create form, I have a 3-tiered dependent dropdown.

For example:

On a Person model I might have the following Country -> State/Province -> City

In the database on the persons table I'm only saving the city_id since I can always look up the state and country via the city.

I have this working on the create form but when someone clicks to edit the form, how can I fill in the country_id and state_province_id since these don't exist from the data?

My code:

Forms\Components\Select::make('country_id')
    ->label('Country')
    ->live()
    ->relationship('country', 'name')
    ->searchable()
    ->preload()
    ->afterStateUpdated(function (Forms\Set $set): void {
        $set('state_province_id', null);
        $set('city_id', null);
    })
    ->dehydrated(false),

Forms\Components\Select::make('state_province_id')
    ->label('State/Province')
    ->live()
    ->disabled(fn (Forms\Get $get): bool => ! filled($get('country_id')))
    ->relationship('stateProvince', 'name')
    ->searchable()
    ->preload()
    ->afterStateUpdated(function (Forms\Set $set): void {
        $set('city_id', null);
    })
    ->dehydrated(false),

Forms\Components\Select::make('city_id')
    ->label('City')
    ->relationship('city', 'name')
    ->searchable()
    ->preload()
    ->required()
    ->exists(City::class, 'id'),
jaunty chasmBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

normal cobalt
#

I tried the field hydration but was getting errors because the state was an array of ids. 1,2,4,5,6,7,8,9,10,11,12,13,14,15

#

I'm assuming the relationship method was grabbing all the countries

#

Additionally, when using the afterStateHydrated() method, it appears this requires an ajax request? It doesn't show on page load for example:

#

In the screenshot, Location = Country, Area = State, Equipment = City. I just changed the models in my original post to make it easier to follow.

normal cobalt
#

I ended up removing the relationship() and opting for a options() and then used the afterStateHydrated() method and it's working. Something about the relationship method isn't working but it looks complicated in the source so I can't figure it out.