Skip to content

Commit

Permalink
Merge pull request #91 from saade/3.x
Browse files Browse the repository at this point in the history
feat: add pivot data
  • Loading branch information
CodeWithDennis authored Mar 6, 2024
2 parents 611a43a + 4fcc9c4 commit 301d518
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/SelectTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
use Filament\Forms\Components\Concerns\CanBeSearchable;
use Filament\Forms\Components\Concerns\HasActions;
use Filament\Forms\Components\Concerns\HasAffixes;
use Filament\Forms\Components\Concerns\HasPivotData;
use Filament\Forms\Components\Concerns\HasPlaceholder;
use Filament\Forms\Components\Contracts\HasAffixActions;
use Filament\Forms\Components\Field;
use Filament\Forms\Form;
use Filament\Support\Facades\FilamentIcon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

class SelectTree extends Field implements HasAffixActions
Expand All @@ -26,6 +28,7 @@ class SelectTree extends Field implements HasAffixActions
use HasActions;
use HasAffixes;
use HasPlaceholder;
use HasPivotData;

protected string $view = 'select-tree::select-tree';

Expand Down Expand Up @@ -101,10 +104,19 @@ protected function setUp(): void
// Check if the component's relationship is a BelongsToMany relationship.
if ($component->getRelationship() instanceof BelongsToMany) {
// Wrap the state in a collection and convert it to an array if it's not set.
$state = Collection::wrap($state ?? []);
$state = Arr::wrap($state ?? []);

$pivotData = $component->getPivotData();

// Sync the relationship with the provided state (IDs).
$component->getRelationship()->sync($state->toArray());
if ($pivotData === []) {
$component->getRelationship()->sync($state ?? []);

return;
}

// Sync the relationship with the provided state (IDs) plus pivot data.
$component->getRelationship()->syncWithPivotValues($state ?? [], $pivotData);
}
});

Expand Down

0 comments on commit 301d518

Please sign in to comment.