diff --git a/README.md b/README.md index e252447..3b49543 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,13 @@ Hide specific options in the tree ->hiddenOptions([2, 3, 4]) ``` +Specify a different key for your model. +For example: you have id, code and parent_code. Your model uses id as key, but the parent-child relation is established between code and parent_code + +```PHP +->withKey('code') +``` + ## 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 932e8ea..949fbf7 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -37,6 +37,8 @@ class SelectTree extends Field implements HasAffixActions protected bool $independent = true; + protected string $customKey = null; + protected string $titleAttribute; protected string $parentAttribute; @@ -111,7 +113,7 @@ protected function setUp(): void $form->model($record)->saveRelationships(); - return $record->getKey(); + return $record->{$this->getCustomKey()}; }); $this->suffixActions([ @@ -184,18 +186,18 @@ private function buildNode($result, $resultMap, $disabledOptions, $hiddenOptions // Create a node with 'name' and 'value' attributes $node = [ 'name' => $result->{$this->getTitleAttribute()}, - 'value' => $result->getKey(), - 'disabled' => in_array($result->getKey(), $disabledOptions), - 'hidden' => in_array($result->getKey(), $hiddenOptions), + 'value' => $result->{$this->getCustomKey()}, + 'disabled' => in_array($result->{$this->getCustomKey()}, $disabledOptions), + 'hidden' => in_array($result->{$this->getCustomKey()}, $hiddenOptions), ]; // Check if the result has children - if (isset($resultMap[$result->getKey()])) { + if (isset($resultMap[$result->{$this->getCustomKey()}])) { $children = collect(); // Recursively build child nodes - foreach ($resultMap[$result->getKey()] as $child) { + foreach ($resultMap[$result->{$this->getCustomKey()}] as $child) { // don't add the hidden ones - if (in_array($child->getKey(), $hiddenOptions)) { + if (in_array($child->{$this->getCustomKey()}, $hiddenOptions)) { continue; } $childNode = $this->buildNode($child, $resultMap, $disabledOptions, $hiddenOptions); @@ -301,6 +303,13 @@ public function independent(bool $independent = true): static return $this; } + public function withKey(string $customKey = 'id'): static + { + $this->customKey = $customKey; + + return $this; + } + public function disabledOptions(Closure|array $disabledOptions): static { $this->disabledOptions = $disabledOptions; @@ -348,6 +357,11 @@ public function getIndependent(): bool { return $this->evaluate($this->independent); } + + public function getCustomKey(): string + { + return $this->customKey ? $this->evaluate($this->customKey) : $this->getKey(); + } public function getWithCount(): bool {