Zalcom
Zalcom
FFilament
Created by Zalcom on 10/2/2024 in #❓┊help
Preselect table Bulk
Hello there ! I'm trying to use a table with BulkActions to update relations between two models. Basically, the point is to create a collections of projects and add on removed said projects from the collection by just selecting/unselecting them on the table. Problem is, I cannot find a way to select by default the records that are already part of the collection. Do you have any ideas ? Here's my component :
class CollectionEdit extends Component implements HasForms, HasTable
{
use InteractsWithTable;
use InteractsWithForms;

public ?array $data = [];
public array $selectedTableRecords = [];
public Collection $collection;

public function mount(Collection $collection = null): void
{
$this->collection = $collection ?? new Collection();
$this->selectedTableRecords = $this->collection->projects()->pluck('id')->map(function ($id) {
return (string)$id;
})->toArray();
$this->form->fill($this->collection->toArray());
}

public function render()
{
return view('livewire.collection-edit');
}

public function table(Table $table): Table
{
return $table
->query(Project::query())
->columns([
TextColumn::make('title')
->label('Titre')
])
->bulkActions([
BulkAction::make('update_collection')
->label('Mettre à jour la collection')
->icon('heroicon-o-arrow-path')
->action(function (\Illuminate\Support\Collection $records) {
$this->selectedTableRecords = $records->pluck('id')->toArray();
$this->collection->projects()->sync($this->selectedTableRecords);
$this->dispatch('collection-updated');
})
->requiresConfirmation()
])
->defaultPaginationPageOption(25);
}
}
class CollectionEdit extends Component implements HasForms, HasTable
{
use InteractsWithTable;
use InteractsWithForms;

public ?array $data = [];
public array $selectedTableRecords = [];
public Collection $collection;

public function mount(Collection $collection = null): void
{
$this->collection = $collection ?? new Collection();
$this->selectedTableRecords = $this->collection->projects()->pluck('id')->map(function ($id) {
return (string)$id;
})->toArray();
$this->form->fill($this->collection->toArray());
}

public function render()
{
return view('livewire.collection-edit');
}

public function table(Table $table): Table
{
return $table
->query(Project::query())
->columns([
TextColumn::make('title')
->label('Titre')
])
->bulkActions([
BulkAction::make('update_collection')
->label('Mettre à jour la collection')
->icon('heroicon-o-arrow-path')
->action(function (\Illuminate\Support\Collection $records) {
$this->selectedTableRecords = $records->pluck('id')->toArray();
$this->collection->projects()->sync($this->selectedTableRecords);
$this->dispatch('collection-updated');
})
->requiresConfirmation()
])
->defaultPaginationPageOption(25);
}
}
2 replies