F
Filamentβ€’2mo ago
Matthew

Table Actions and making variables more efficient

Interested in any opinions on how people avoid repeating code for issues where a table action, and elements of that are dependent on the status of $record For example, if:
Action::make('test')
->button()
->label(function ($record) :string {

if ($record->isTypeA())
{return 'Some text';
})

if $record->isTypeB())
{return 'Some different text';
})

->tooltip(function ($record) :string {

if ($record->isTypeA())
{return 'Some tootip text';
})

if $record->isTypeB())
{return 'Some different tooltip text';
}),
Action::make('test')
->button()
->label(function ($record) :string {

if ($record->isTypeA())
{return 'Some text';
})

if $record->isTypeB())
{return 'Some different text';
})

->tooltip(function ($record) :string {

if ($record->isTypeA())
{return 'Some tootip text';
})

if $record->isTypeB())
{return 'Some different tooltip text';
}),
Obviously a very basic example, but when you start adding a lot more methods, and increasing the complexity of the options, it can feel very cluttered and inefficient. How do people go about extracting some of this logic for the $record?
4 Replies
Lara Zeus
Lara Zeusβ€’2mo ago
you can do:
$record->getLabel($type)
$record->getLabel($type)
and add the method getLabel on the model, and the same for the tooltip
trovster
trovsterβ€’2mo ago
Implementing getLabel() on the model might help. There is an interface/contract for this, which I use for Enums;
<?php

namespace Filament\Support\Contracts;

interface HasLabel
{
public function getLabel(): ?string;
}
<?php

namespace Filament\Support\Contracts;

interface HasLabel
{
public function getLabel(): ?string;
}
Matthew
MatthewOPβ€’2mo ago
Thanks for the input...I'm wondering whether there are any approaches that are a bit more encompassing? The label and tooltip were just for illustration. What if I've got 12 different methods with variations ? I could load the functions into a model trait. But I just wanted to check there wasn't an easier way to extract the $record, and re-inject the maniuplated statuses back into all the chainable methods.
Lara Zeus
Lara Zeusβ€’2mo ago
there is also configerUsing but I think the $record wont be initialized till the form has been built, other approach it to create a macro it may help, it really depend on your use case πŸ™‚
Want results from more Discord servers?
Add your server