Dynamic select options from external api

Hello everyone,

I am currently trying to fill a select field in Filament with cities after I have entered the zip code. However, it doesn't really work.
Can anyone tell me how to do this correctly?
I'm sure it's far too complicated at the moment.

My first solution:
TextInput::make('postal_code')
  ->label('Postleitzahl')
  ->required()
  ->afterStateUpdated(function (Get $get, ?string $state, Set $set) use ($serviceInstance) {
    if (strlen($state) === 5 && $get('country') === 'DE') {
      self::$cities = $serviceInstance->loadCities($state);
      
      if (isset(self::$cities['message'])) {
        Notification::make()
          ->title(self::$cities['message'])
          ->danger()
          ->send();
      }
      
      if (count(self::$cities) === 1) {
        $set('city', self::$cities[0]);
      }
    }
    
    if ($state === null) {
      $set('city', '');
    }
  })
  ->live(),
Select::make('city')
  ->label('Stadt/Ort')
  ->options(self::$cities)
  ->live()
  ->searchable()
  ->required(),


My current solution:
TextInput::make('postal_code')
    ->label('Postleitzahl')
    ->required()
    ->afterStateUpdated(function (?string $state, Set $set) {
        if ($state === null) {
            $set('city', '');
        }
    })
    ->reactive()
    ->live(),
Select::make('city')
    ->label('Stadt/Ort')
    ->options(function (Get $get) {
        if ($get('postal_code') !== null && strlen($get('postal_code') === 5)) {
            return GeoLocationHelper::getInstance()->loadCities($get('postal_code'));
        }
        
        return [];
    })
    ->reactive()
    ->required(),
Was this page helpful?