Skip to main content
Tutorial Free

Filament: Input Prefix/Suffix - Dynamic Based on Other Input

November 17, 2023
2 min read

When working on Filament forms - you might have used suffixes and prefixes. But did you know that they can be dynamic? For example, you can switch suffixes/prefixes dynamically based on a selection. Let's see how to do that!

In our example, we will make dynamic suffixes/prefixes auto-change based on our invoice currency. So first, we need a currency selection:

Resource

// ...
 
Forms\Components\Select::make('currency')
->options([
'usd' => 'USD',
'eur' => 'EUR',
'gbp' => 'GBP',
])
->default('usd')
// We need this field to trigger a livewire update on the change
->live()
 
// ...

Next, we need a field that will be dynamic. In our case, this will be subtotal and total fields:

Resource

// ...
 
Forms\Components\Select::make('currency')
->options([
'usd' => 'USD',
'eur' => 'EUR',
'gbp' => 'GBP',
])
->default('usd')
// We need this field to trigger a livewire update on the change
->live()
 
Forms\Components\TextInput::make('subtotal')
->prefix(function (Get $get) {
return match ($get('currency')) {
'usd' => '$',
'gbp' => '£',
default => null
};
})
->suffix(function (Get $get) {
return match ($get('currency')) {
'eur' => '',
default => null,
};
}),
Forms\Components\TextInput::make('total')
->prefix(function (Get $get) {
return match ($get('currency')) {
'usd' => '$',
'gbp' => '£',
default => null
};
})
->suffix(function (Get $get) {
return match ($get('currency')) {
'eur' => '',
default => null,
};
})
 
// ...

Now, if we open up the page, we can see that changing our currency will change the prefix/suffix of our fields:

For USD:

For EUR:

For GBP:

This is achieved due to these things:

  • Our Currency field is set to be dynamic
  • Our prefix and suffix use php match to check what we need to display based on the select
  • It used a clever rule where null is counted as no prefix/suffix, so we can switch them dynamically

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.