Skip to content

Commit 1ab3589

Browse files
Merge pull request #166 from gp-lnuff/3.x
Add append feature
2 parents 5ec4a6f + 2751081 commit 1ab3589

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,25 @@ use CodeWithDennis\FilamentSelectTree\SelectTree;
223223
])
224224
```
225225

226+
If you need to append an item to the tree menu, use the `append` method. This method also accepts an array or a closure.
227+
228+
```php
229+
->schema([
230+
SelectTree::make('category')
231+
->relationship('categories', 'name', 'parent_id')
232+
->enableBranchNode()
233+
->multiple(false)
234+
->append([
235+
'name' => 'Uncategorized Records',
236+
'value' => -1,
237+
'parent' => null, // optional
238+
'disabled' => false, // optional
239+
'hidden' => false, // optional
240+
'children' => [], // optional
241+
])
242+
])
243+
```
244+
226245
## Filters
227246

228247
Use the tree in your table filters. Here's an example to show you how.

src/SelectTree.php

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ class SelectTree extends Field implements HasAffixActions
8888

8989
protected Closure|array|null $prepend = null;
9090

91+
protected Closure|array|null $append = null;
92+
9193
protected Closure|string|null $treeKey = 'treeKey';
9294

9395
protected function setUp(): void
@@ -316,6 +318,19 @@ public function prepend(Closure|array|null $prepend = null): static
316318
return $this;
317319
}
318320

321+
public function append(Closure|array|null $append = null): static
322+
{
323+
$this->append = $this->evaluate($append);
324+
325+
if (is_array($this->append) && isset($this->append['name'], $this->append['value'])) {
326+
$this->append['value'] = (string) $this->append['value'];
327+
} else {
328+
throw new \InvalidArgumentException('The provided append value must be an array with "name" and "value" keys.');
329+
}
330+
331+
return $this;
332+
}
333+
319334
public function getRelationship(): BelongsToMany|BelongsTo
320335
{
321336
return $this->getModelInstance()->{$this->evaluate($this->relationship)}();
@@ -422,8 +437,10 @@ public function storeResults(bool $storeResults = true): static
422437

423438
public function getTree(): Collection|array
424439
{
425-
return $this->evaluate($this->buildTree()->when($this->prepend,
426-
fn (Collection $tree) => $tree->prepend($this->evaluate($this->prepend))));
440+
return $this->evaluate($this->buildTree()
441+
->when($this->prepend, fn (Collection $tree) => $tree->prepend($this->evaluate($this->prepend)))
442+
->when($this->append, fn (Collection $tree) => $tree->push($this->evaluate($this->append)))
443+
);
427444
}
428445

429446
public function getResults(): Collection|array|null

0 commit comments

Comments
 (0)