@@ -37,6 +37,8 @@ class SelectTree extends Field implements HasAffixActions
3737
3838 protected bool $ independent = true ;
3939
40+ protected ?string $ customKey = null ;
41+
4042 protected string $ titleAttribute ;
4143
4244 protected string $ parentAttribute ;
@@ -111,7 +113,7 @@ protected function setUp(): void
111113
112114 $ form ->model ($ record )->saveRelationships ();
113115
114- return $ record -> getKey ( );
116+ return $ this -> getCustomKey ( $ record );
115117 });
116118
117119 $ this ->suffixActions ([
@@ -181,22 +183,24 @@ private function buildTreeFromResults($results, $parent = null): Collection
181183
182184 private function buildNode ($ result , $ resultMap , $ disabledOptions , $ hiddenOptions ): array
183185 {
186+ $ key = $ this ->getCustomKey ($ result );
187+
184188 // Create a node with 'name' and 'value' attributes
185189 $ node = [
186190 'name ' => $ result ->{$ this ->getTitleAttribute ()},
187- 'value ' => $ result -> getKey () ,
191+ 'value ' => $ key ,
188192 'parent ' => $ result ->{$ this ->getParentAttribute ()},
189- 'disabled ' => in_array ($ result -> getKey () , $ disabledOptions ),
190- 'hidden ' => in_array ($ result -> getKey () , $ hiddenOptions ),
193+ 'disabled ' => in_array ($ key , $ disabledOptions ),
194+ 'hidden ' => in_array ($ key , $ hiddenOptions ),
191195 ];
192196
193197 // Check if the result has children
194- if (isset ($ resultMap [$ result -> getKey () ])) {
198+ if (isset ($ resultMap [$ key ])) {
195199 $ children = collect ();
196200 // Recursively build child nodes
197- foreach ($ resultMap [$ result -> getKey () ] as $ child ) {
201+ foreach ($ resultMap [$ key ] as $ child ) {
198202 // don't add the hidden ones
199- if (in_array ($ child -> getKey ( ), $ hiddenOptions )) {
203+ if (in_array ($ this -> getCustomKey ( $ child ), $ hiddenOptions )) {
200204 continue ;
201205 }
202206 $ childNode = $ this ->buildNode ($ child , $ resultMap , $ disabledOptions , $ hiddenOptions );
@@ -302,6 +306,13 @@ public function independent(bool $independent = true): static
302306 return $ this ;
303307 }
304308
309+ public function withKey (string $ customKey ): static
310+ {
311+ $ this ->customKey = $ customKey ;
312+
313+ return $ this ;
314+ }
315+
305316 public function disabledOptions (Closure |array $ disabledOptions ): static
306317 {
307318 $ this ->disabledOptions = $ disabledOptions ;
@@ -350,6 +361,11 @@ public function getIndependent(): bool
350361 return $ this ->evaluate ($ this ->independent );
351362 }
352363
364+ public function getCustomKey ($ record )
365+ {
366+ return is_null ($ this ->customKey ) ? $ record ->getKey () : $ record ->{$ this ->customKey };
367+ }
368+
353369 public function getWithCount (): bool
354370 {
355371 return $ this ->evaluate ($ this ->withCount );
0 commit comments