Skip to content

Commit a811ee3

Browse files
Added modifyQueryUsing closure
1 parent bed8555 commit a811ee3

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

src/SelectTree.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Filament\Forms\Components\Concerns\HasPlaceholder;
88
use Filament\Forms\Components\Field;
99
use Illuminate\Support\Collection;
10+
use Closure;
1011

1112
class SelectTree extends Field
1213
{
@@ -26,6 +27,8 @@ class SelectTree extends Field
2627

2728
protected string $titleAttribute;
2829

30+
protected ?Closure $modifyQueryUsing;
31+
2932
public function withCount(bool $withCount = true): static
3033
{
3134
$this->withCount = $withCount;
@@ -55,30 +58,43 @@ public function getDisabledBranchNode(): bool
5558
return $this->evaluate($this->disabledBranchNode);
5659
}
5760

58-
public function tree(string $treeModel, string $treeParentKey, string $titleAttribute): static
61+
public function tree(string $treeModel, string $treeParentKey, string $titleAttribute, ?Closure $modifyQueryUsing = null): static
5962
{
6063
$this->treeModel = $treeModel;
6164
$this->treeParentKey = $treeParentKey;
6265
$this->titleAttribute = $titleAttribute;
66+
$this->modifyQueryUsing = $modifyQueryUsing;
6367

6468
return $this;
6569
}
66-
70+
6771
private function buildTree(int $parent = null): Collection
6872
{
73+
// Create a default query to fetch items with the specified parent ID.
74+
$defaultQuery = $this->treeModel::query()
75+
->where($this->treeParentKey, $parent);
76+
77+
// If not a root level query and a modification callback is provided, apply it.
78+
if (!$parent && $this->modifyQueryUsing) {
79+
$defaultQuery = $this->evaluate($this->modifyQueryUsing, ['query' => $defaultQuery]);
80+
}
6981

70-
// TEST CODE
71-
$results = $this->treeModel::where($this->treeParentKey, $parent)
72-
->get();
82+
// Fetch the results from the default query.
83+
$results = $defaultQuery->get();
7384

85+
// Map the results into a tree structure.
7486
return $results->map(function ($result) {
87+
88+
// Recursively build children trees for the current result.
7589
$children = $this->buildTree($result->id);
7690

91+
// Create an array representation of the current result with children.
7792
return [
7893
'name' => $result->{$this->titleAttribute},
7994
'value' => $result->id,
8095
'children' => $children->isEmpty() ? null : $children->toArray(),
8196
];
8297
});
8398
}
99+
84100
}

0 commit comments

Comments
 (0)