Skip to content

Method for create custom tree #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from
Open
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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,29 @@ Specify the list's force direction. Options include: auto (default), top, and bo
->direction('top')
```

Customize how the tree is built with a custom callback function

```php
->getTreeUsing(function () {
// Build and return your custom tree structure as a Collection
return collect([
[
'name' => 'Custom Category 1',
'value' => 1,
'parent' => null,
'children' => [
[
'name' => 'Subcategory 1.1',
'value' => 2,
'parent' => 1,
'children' => []
]
]
]
]);
})
```

Display individual leaf nodes instead of the main group when all leaf nodes are selected

```php
Expand Down
15 changes: 14 additions & 1 deletion src/SelectTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ class SelectTree extends Field implements HasAffixActions

protected Closure|array|null $prepend = null;

protected ?Closure $getTreeUsing = null;

protected function setUp(): void
{
// Load the state from relationships using a callback function.
Expand Down Expand Up @@ -149,6 +151,10 @@ protected function setUp(): void

protected function buildTree(): Collection
{
if ($this->getTreeUsing) {
return $this->evaluate($this->getTreeUsing);
}

// Start with two separate query builders
$nullParentQuery = $this->getRelationship()->getRelated()->query()->where($this->getParentAttribute(), $this->getParentNullValue());
$nonNullParentQuery = $this->getRelationship()->getRelated()->query()->whereNot($this->getParentAttribute(), $this->getParentNullValue());
Expand Down Expand Up @@ -418,7 +424,7 @@ public function getTree(): Collection|array

public function getResults(): Collection|array|null
{
return $this->evaluate($this->results);
return $this->results;
}

public function getExpandSelected(): bool
Expand Down Expand Up @@ -614,4 +620,11 @@ public function createOptionModalHeading(string|Closure|null $heading): static

return $this;
}

public function getTreeUsing(?Closure $callback): static
{
$this->getTreeUsing = $callback;

return $this;
}
}