Skip to content

Commit 28fd141

Browse files
Merge pull request #24 from CodeWithDennis/23-nullvalue
Implemented `parentNullValue`
2 parents 8557f65 + 4bfb19f commit 28fd141

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ SelectTree::make('category_id')
6161
// Set nodes as dependent
6262
->independent(false)
6363

64+
// Set the parent's null value to -1, allowing you to use -1 as a sentinel value (default = null)
65+
->parentNullValue(-1)
66+
6467
// Expand the tree with selected values
6568
->expandSelected(false)
6669

src/SelectTree.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ class SelectTree extends Field
3131

3232
protected string $parentAttribute;
3333

34+
protected null|int|string $parentNullValue = null;
35+
3436
protected bool $clearable = true;
3537

3638
protected bool $expandSelected = true;
@@ -79,8 +81,11 @@ protected function setUp(): void
7981
});
8082
}
8183

82-
private function buildTree(int $parent = null): array|Collection
84+
private function buildTree($parent = null): array|Collection
8385
{
86+
// Assign the parent's null value to the $parent variable if it's not null
87+
$parent = $this->getParentNullValue() ?? $parent;
88+
8489
// Create a default query to retrieve related items.
8590
$defaultQuery = $this->getRelationship()
8691
->getRelated()
@@ -134,6 +139,13 @@ public function direction(string $direction): static
134139
return $this;
135140
}
136141

142+
public function parentNullValue(int|string $parentNullValue = null): static
143+
{
144+
$this->parentNullValue = $parentNullValue;
145+
146+
return $this;
147+
}
148+
137149
public function getRelationship(): BelongsToMany|BelongsTo
138150
{
139151
return $this->getModelInstance()->{$this->evaluate($this->relationship)}();
@@ -149,6 +161,11 @@ public function getParentAttribute(): string
149161
return $this->evaluate($this->parentAttribute);
150162
}
151163

164+
public function getParentNullValue(): null|int|string
165+
{
166+
return $this->evaluate($this->parentNullValue);
167+
}
168+
152169
public function clearable(bool $clearable = true): static
153170
{
154171
$this->clearable = $clearable;

0 commit comments

Comments
 (0)