Dynamic toggle columns based on relationship

So, I have this model Product, which links to ProductCountry (which is also linked to a Country) In my Product-table I would like to have a column for every Country with a toggle-button which indicates whether that product is enabled for that country. When clicking the toggle-button, it should either add the ProductCountry-record to the database, or delete it. How would I make this possible in Filamentphp?
4 Replies
Kikechi
Kikechi3w ago
@Strangler try this and see if it can inspire a working solution
No description
Strangler
StranglerOP3w ago
@Kikechi Oh wow, that helped me a lot! Thank you so much!
ModestasV
ModestasV3w ago
It also can be done like this:
class ProductsTable
{
public static function configure(Table $table): Table
{

$countryColumns = Country::all()->map(function (Country $country) {
return CheckboxColumn::make('productCountries.' . $country->id)
->state(function (CheckboxColumn $column, $record) use ($country) {
return $record->productCountries->contains('country_id', $country->id);
})
->updateStateUsing(function (CheckboxColumn $column, $record, $state) use ($country) {
if ($state) {
ProductCountry::create([
'product_id' => $record->id,
'country_id' => $country->id
]);
} else {
ProductCountry::where('product_id', $record->id)
->where('country_id', $country->id)
->delete();
}
})
->label($country->name);
});

return $table
->columns([
TextColumn::make('id'),
TextColumn::make('name'),
...$countryColumns,
])
->filters([
//
])
->recordActions([
ViewAction::make(),
EditAction::make(),
])
->toolbarActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
]),
]);
}
}
class ProductsTable
{
public static function configure(Table $table): Table
{

$countryColumns = Country::all()->map(function (Country $country) {
return CheckboxColumn::make('productCountries.' . $country->id)
->state(function (CheckboxColumn $column, $record) use ($country) {
return $record->productCountries->contains('country_id', $country->id);
})
->updateStateUsing(function (CheckboxColumn $column, $record, $state) use ($country) {
if ($state) {
ProductCountry::create([
'product_id' => $record->id,
'country_id' => $country->id
]);
} else {
ProductCountry::where('product_id', $record->id)
->where('country_id', $country->id)
->delete();
}
})
->label($country->name);
});

return $table
->columns([
TextColumn::make('id'),
TextColumn::make('name'),
...$countryColumns,
])
->filters([
//
])
->recordActions([
ViewAction::make(),
EditAction::make(),
])
->toolbarActions([
BulkActionGroup::make([
DeleteBulkAction::make(),
]),
]);
}
}
No description
Misbach
Misbach3w ago
Yes

Did you find this page helpful?