Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,66 @@ If you need to append an item to the tree menu, use the `append` method. This me
])
```

If you need full control over the tree structure, you can use `getTreeUsing` to provide a custom tree array, or a closure that resolves to an array.

Using an array:

```php
SelectTree::make('categories')
->getTreeUsing([
[
'name' => 'Parent Category',
'value' => '1',
'children' => [
[
'name' => 'Child Category',
'value' => '2',
'children' => [],
],
],
],
[
'name' => 'Another Category',
'value' => '3',
'children' => [],
],
])
```

Using a closure for dynamic data:

```php
SelectTree::make('categories')
->getTreeUsing(function () {
return Category::query()
->get()
->map(fn ($category) => [
'name' => $category->name,
'value' => $category->id,
'children' => $category->children->map(fn ($child) => [
'name' => $child->name,
'value' => $child->id,
'children' => [],
])->toArray(),
])
->toArray();
})
```

The tree structure should follow this format:

```php
[
[
'name' => 'Display Name',
'value' => 'option_value',
'disabled' => false, // optional
'hidden' => false, // optional
'children' => [], // optional
],
]
```

## Filters

Use the tree in your table filters. Here's an example to show you how.
Expand Down
13 changes: 13 additions & 0 deletions src/SelectTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ class SelectTree extends Field implements HasAffixActions

protected bool $storeResults = false;

protected Closure|array|null $getTreeUsing = null;

protected LazyCollection|array|null $results = null;

protected Closure|bool|null $multiple = null;
Expand Down Expand Up @@ -542,8 +544,19 @@ public function storeResults(bool $storeResults = true): static
return $this;
}

public function getTreeUsing(Closure|array $value): static
{
$this->getTreeUsing = $value;

return $this;
}

public function getTree(): Collection|array
{
if ($this->getTreeUsing) {
return $this->evaluate($this->getTreeUsing);
}

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)))
Expand Down