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

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials