Dmitriy
Dmitriy
FFilament
Created by Dmitriy on 2/21/2025 in #❓┊help
TextColumn throwing an exception for the empty ENUM value
I have an attribute called language that is often used in several tables and for now 3 language codes could be used as values. So, I created an Enum class App\Enums\Language and in the Eloquent model the attribute language is cast correctly:
protected $casts = [
'language' => App\Enums\Language::class,
];
protected $casts = [
'language' => App\Enums\Language::class,
];
In the related Filament Resource I have a dropdown field for the form:
return $form
->schema([
Filament\Forms\Components\Select::make('language')
->nullable()
->options(App\Enums\Language::class)
]);
return $form
->schema([
Filament\Forms\Components\Select::make('language')
->nullable()
->options(App\Enums\Language::class)
]);
And a text column for the list table:
return $table
->columns([
Filament\Tables\Columns\TextColumn::make('language')
->sortable()
->badge()
]);
return $table
->columns([
Filament\Tables\Columns\TextColumn::make('language')
->sortable()
->badge()
]);
As the result, on the Edit and Create pages the dropdown shows available labels from the Enum class and everything works as it should. But the problem that some of the existing records don't have a value for the attribute language . And as the result, on the List page an exception is throwing with the message "" is not a valid backing value for enum App\Enums\Language. I found a lot of related articles but still wasn't able to fix it. For example this one https://www.answeroverflow.com/m/1184219387109068871 Here https://medium.com/@yihen_26052/the-magic-from-method-of-enum-in-php-8-1-ad5a1a8f9298 also there is a good explanation between Enum ::from() and ::tryFrom() methods. It seems that method tryFrom returns null for invalid values instead of throwing an exception. Maybe this could be a good fix for such case and could be fixed in the upcoming Filament version? Or probably there is some workaround to avoid the error? I would also be grateful if you could suggest what else could be used to move the repeating code into one place. I know about the option of creating a separate table for languages ​​in the database and linking it to the existing records. But for now I would like to put the list of languages in some PHP class.
8 replies