Hello,I have a Table column like this:

Tables\Columns\TextColumn::make('distances.lenght')
->listWithLineBreaks()
->badge()
->prefix('km ')
->sortable(),
Tables\Columns\TextColumn::make('distances.lenght')
->listWithLineBreaks()
->badge()
->prefix('km ')
->sortable(),
where distances is an HasMany relationship. The question is: how to change the badge color for each distance and the suffix using a property of the distance? I have a boolean field in distances table (is_competitive), and if it's true I want a color different from the false one
8 Replies
Jordy
Jordy3w ago
->color(fn($record) => ...) ->suffix(fn$record)=> ...) just add your logic, most methods accept a closure
capins
capinsOP3w ago
Thankyou Jordy, the way is correct, but the solution is to change the column in
Tables\Columns\TextColumn::make('distances')
Tables\Columns\TextColumn::make('distances')
with the whole relationship, and then inside use
Tables\Columns\TextColumn::make('distances')
->formatStateUsing(fn($state) => $state->lenght)
->listWithLineBreaks()
->badge()
->color(fn($state) => $state->is_competitive ? 'success' : 'info')
->prefix('km ')
->suffix(fn($state) => $state->is_competitive ? 'n.c.' : '')
->sortable(),
Tables\Columns\TextColumn::make('distances')
->formatStateUsing(fn($state) => $state->lenght)
->listWithLineBreaks()
->badge()
->color(fn($state) => $state->is_competitive ? 'success' : 'info')
->prefix('km ')
->suffix(fn($state) => $state->is_competitive ? 'n.c.' : '')
->sortable(),
but the weird think is that color and formatstateusing work great, but suffix return an error, because inside suffix the state is a collection and not a eloquen model
Jordy
Jordy3w ago
because distances is a relationship, the state of the column is the collection of related distances
capins
capinsOP3w ago
Yes, but in color and in formatStateUsing is the EloquentModel. So it handle the state in a different way
Jordy
Jordy3w ago
I think that has to do with your usage of ->listWithLineBreaks() I recreated it quickly and when I remove that it throws Attempt to read property on string seems filament is smart enough to format the state for each record, but the suffix seems to be for the entire column adding your suffix logic into ->formatStateUsing() seems the easiest fix
capins
capinsOP3w ago
you're right.. it's the easiest way Thanks I need to sort the list by an attribute, but I don't think it's possibile
Jordy
Jordy3w ago
perhaps if you already sort the distances in the original table query? This works for me
->query(Model::query()->with('relation', fn($query) => $query->orderBy('column')))
->query(Model::query()->with('relation', fn($query) => $query->orderBy('column')))
capins
capinsOP3w ago
great!

Did you find this page helpful?