diff --git a/README.md b/README.md index f5c7bcc..6dffb26 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/SelectTree.php b/src/SelectTree.php index 3f0eb8e..4bb9e26 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -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; @@ -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)))