Tricks

Call external API and return dropdown options

Oct 7, 2022
mikrosmile
Admin panel, Form builder

There is an easy way how to call external API and return results in dropdown in filament.

First: You need to define an action (it can be either Button or any other element with action()

action() method is actually what will be performed when form is 'submitted' so, inside the action you need to place the actual thing you want to perform with the form:

e.g: In this example I'm using Filament/Action on CreateRecord class, when I hit submit, the form will be filled with the desired option

protected function getActions(): array
{
return [
Actions\Action::make('foo')
->action(function ($data){
$this->form->fill([
'bar' => $data['select']['data1'] // <- here we will get options from out Select
]);
})
->form(function(){
$array = $apiDATA['api']; // <- here you should place your api return method (direct URL, plugin method, etc) which
 
$options = collect([]);
 
for ($i = 0; $i < count($array); $i++) {
$data1 = $array[$i]['data1'];
$data2 = $array[$i]['data2'];
$value = $data1.''.$data2;
$options->push($value); // <- This is options for Select
}
 
return [
Select::make('select')
->options($options) // <- $options is a simple array which we will get data from API
];
}),

No comments yet…