77use Filament \Forms \Components \Concerns \HasPlaceholder ;
88use Filament \Forms \Components \Field ;
99use Illuminate \Support \Collection ;
10+ use Closure ;
1011
1112class 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