By default, the ToggleColumn in Laravel Filament is designed to work with boolean-like fields. However, there may be cases where you need to customize it to work with different data like textual fields.
Solution
This can be achieved by customizing the ToggleColumn using the getStateUsing() and updateStateUsing() methods.
Example
One such example is when you want to simplify the activation of new users directly from the table, allowing you to switch between the status of ‘pending’ and ‘activated’.
By utilizing the getStateUsing() method, you can define a callback that retrieves the current state of the field, such as checking if the status is ‘activated’. This allows you to determine the initial state of the toggle.
To update the state of the toggle, you can use the updateStateUsing() method. This method allows you to define a callback that transforms the boolean value of the toggle to a textual representation, such as converting true to ‘activated’ and false to ‘pending’.
By customizing the ToggleColumn in this way, you can simplify the process of activating new users directly from the table, providing a convenient way to switch between the ‘pending’ and ‘activated’ options.
public function up()
{
Schema::create('members', function (Blueprint $table) {
//...
$table->enum('status', ['activated','pending','suspended', 'deleted'])
->defaul('pending');
});
}public static function form(Form $form): Form
{
return $form
->schema([
//...
Forms\Components\Select::make('status')
->options(['activated','pending','suspended', 'deleted']),
])
}
public static function table(Table $table): Table
{
return $table
->columns([
//...
Tables\Columns\ToggleColumn::make('status')
->getStateUsing(function (Member $record) {
return (bool) ($record->status == 'activated');
})->updateStateUsing(function ($state, Member $record) {
$record->status = $state ? 'activated' : 'pending';
$record->save();
return $state;
}),
])
}
Comments