From 83e9bfa2b54063247d148681a0ff032c82178ac2 Mon Sep 17 00:00:00 2001 From: gp-lnuff Date: Mon, 21 Jul 2025 17:21:54 +0200 Subject: [PATCH] Add Append Feature --- README.md | 19 +++++++++++++++++++ src/SelectTree.php | 20 ++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1d4d1fe..a34199c 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,25 @@ use CodeWithDennis\FilamentSelectTree\SelectTree; ]) ``` +If you need to append an item to the tree menu, use the `append` method. This method also accepts an array or a closure. + +```php +->schema([ + SelectTree::make('category') + ->relationship('categories', 'name', 'parent_id') + ->enableBranchNode() + ->multiple(false) + ->append([ + 'name' => 'Uncategorized Records', + 'value' => -1, + 'parent' => null, // optional + 'disabled' => false, // optional + 'hidden' => false, // optional + 'children' => [], // optional + ]) + ]) +``` + ## Filters Use the tree in your table filters. Here's an example to show you how. diff --git a/src/SelectTree.php b/src/SelectTree.php index f1c0918..93ec5aa 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -88,6 +88,8 @@ class SelectTree extends Field implements HasAffixActions protected Closure|array|null $prepend = null; + protected Closure|array|null $append = null; + protected Closure|string|null $treeKey = 'treeKey'; protected function setUp(): void @@ -316,6 +318,18 @@ public function prepend(Closure|array|null $prepend = null): static return $this; } + public function append(Closure|array|null $append = null): static { + $this->append = $this->evaluate($append); + + if (is_array($this->append) && isset($this->append['name'], $this->append['value'])) { + $this->append['value'] = (string) $this->append['value']; + } else { + throw new \InvalidArgumentException('The provided append value must be an array with "name" and "value" keys.'); + } + + return $this; + } + public function getRelationship(): BelongsToMany|BelongsTo { return $this->getModelInstance()->{$this->evaluate($this->relationship)}(); @@ -422,8 +436,10 @@ public function storeResults(bool $storeResults = true): static public function getTree(): Collection|array { - return $this->evaluate($this->buildTree()->when($this->prepend, - fn (Collection $tree) => $tree->prepend($this->evaluate($this->prepend)))); + return $this->evaluate($this->buildTree() + ->when($this->prepend, fn(Collection $tree) => $tree->prepend($this->evaluate($this->prepend))) + ->when($this->append, fn(Collection $tree) => $tree->push($this->evaluate($this->append))) + ); } public function getResults(): Collection|array|null