Update a field based on select value
I have a field called 'Country' where a user can select a value. When a user selects a country, it gets stored in the database.
Select::make('country')
->required()
->native(false)
->options(Country::class)
->dehydrated(false),
I want to write a two letter country code to another field in the database (e.g country_iso) each time the user selects a value in the above select box. So if a user selects 'Netherlands' I want to write 'Netherlands' to the 'country' field, but also 'NL' in the billing_country.
As a test, in the below snippet, I tried to update the Text Input to display the selected option but that does not work.
Select::make('country')
->required()
->native(false)
->options(Country::class)
->dehydrated(false)
->afterStateUpdated(function (Set $set, ?string $state) {
$set('country', $state);
$set('billing_country_placeholder', $state ? "Selected country: $state" : 'No country selected');
}),
TextInput::make('billing_country')
->live()
->placeholder(fn (Get $get): string => $get('billing_country_placeholder') ?? 'No country selected')
3 Replies
The Select field needs to be
->live()
because it's the one changing.you don't need to use
afterStateUpdated
$set
if you want to change only the placeholder
Thanks. This works perfectly!