FilamentF
Filament10mo ago
Nico

Set multiple properties on the same field

What I am trying to do:
I have a company model which contains the following fields: address, city, zipcode, country and location (postgres geography column: latitude, longitude).
I'm attempting to use a Google Maps autocomplete to fill out all of the models on the property from what is returned from the autocomplete field.
I would just like to know if there is a simple way to send multiple properties to the view and receive multiple properties back from the view when saving.

What I did:
I've tried some of the plugins that already exist but I haven't had success configuring them to work exactly how I would like it.

My issue/the error:
The current solution works fine when editing an existing company but when it's used to create a new the dehydrateStateUsing doesn't seem to apply the properties correctly.

Code:
The TextInput used:
TextInput::make('address')
    ->label('Address')
    ->view('forms.components.address-autocomplete')
    ->afterStateHydrated(static function (TextInput $component) {
        $company = $component->getModelInstance();

        $component->state([
            'address' => $company->address,
            'city' => $company->city,
            'zipcode' => $company->zipcode,
            'country' => $company->country,
            'location' => $company->location?->toJson(),
        ]);
    })
    ->dehydrateStateUsing(static function (TextInput $component, string|array $state, Set $set) {
        if (is_string($state)) {
            return $state;
        }

        $company = $component->getModelInstance();
        $company->address = $state['address'] ?? null;
        $company->city = $state['city'] ?? null;
        $company->zipcode = $state['zipcode'] ?? null;
        $company->country = $state['country'] ?? null;
        $company->location = Point::fromArray($state['location']);

        return $state['address'];
    }),

The address autocomplete blade view is attached
Was this page helpful?