Skip to content

Commit

Permalink
Merge pull request #24 from CodeWithDennis/23-nullvalue
Browse files Browse the repository at this point in the history
Implemented `parentNullValue`
  • Loading branch information
CodeWithDennis authored Sep 25, 2023
2 parents 8557f65 + 4bfb19f commit 28fd141
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ SelectTree::make('category_id')
// Set nodes as dependent
->independent(false)

// Set the parent's null value to -1, allowing you to use -1 as a sentinel value (default = null)
->parentNullValue(-1)

// Expand the tree with selected values
->expandSelected(false)

Expand Down
19 changes: 18 additions & 1 deletion src/SelectTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class SelectTree extends Field

protected string $parentAttribute;

protected null|int|string $parentNullValue = null;

protected bool $clearable = true;

protected bool $expandSelected = true;
Expand Down Expand Up @@ -79,8 +81,11 @@ protected function setUp(): void
});
}

private function buildTree(int $parent = null): array|Collection
private function buildTree($parent = null): array|Collection
{
// Assign the parent's null value to the $parent variable if it's not null
$parent = $this->getParentNullValue() ?? $parent;

// Create a default query to retrieve related items.
$defaultQuery = $this->getRelationship()
->getRelated()
Expand Down Expand Up @@ -134,6 +139,13 @@ public function direction(string $direction): static
return $this;
}

public function parentNullValue(int|string $parentNullValue = null): static
{
$this->parentNullValue = $parentNullValue;

return $this;
}

public function getRelationship(): BelongsToMany|BelongsTo
{
return $this->getModelInstance()->{$this->evaluate($this->relationship)}();
Expand All @@ -149,6 +161,11 @@ public function getParentAttribute(): string
return $this->evaluate($this->parentAttribute);
}

public function getParentNullValue(): null|int|string
{
return $this->evaluate($this->parentNullValue);
}

public function clearable(bool $clearable = true): static
{
$this->clearable = $clearable;
Expand Down

0 comments on commit 28fd141

Please sign in to comment.