Skip to content

Commit

Permalink
feat: add defaultCallback method
Browse files Browse the repository at this point in the history
  • Loading branch information
binaryk committed Dec 4, 2024
1 parent 2da856d commit a2c7abd
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Fields/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ class Field extends OrganicField implements JsonSerializable
*/
protected $valueCallback;

protected $fillDefaultCallback;

/**
* Closure be used to be called after the field value stored.
*/
Expand Down Expand Up @@ -205,6 +207,13 @@ public function fillCallback(callable|Closure $callback)
return $this;
}

public function defaultCallback(mixed $callback)
{
$this->defaultCallback = $callback;

return $this;
}

/**
* Fill attribute with value from the request or delegate this action to the user defined callback.
*
Expand Down Expand Up @@ -246,6 +255,12 @@ public function fillAttribute(RestifyRequest $request, $model, ?int $bulkRow = n
$bulkRow
);

$this->fillAttributeFromDefault(
$request,
$model,
$this->label ?? $this->attribute
);

$this->fillAttributeFromValue(
$request,
$model,
Expand Down Expand Up @@ -310,6 +325,23 @@ protected function fillAttributeFromValue(RestifyRequest $request, $model, $attr
return $this;
}

protected function fillAttributeFromDefault(RestifyRequest $request, $model, $attribute)
{
if ($model->{$attribute}) {
return $this;
}

if (! isset($this->fillDefaultCallback)) {
return $this;
}

$model->{$attribute} = is_callable($this->fillDefaultCallback)
? call_user_func($this->fillDefaultCallback, $request, $model, $attribute)
: $this->fillDefaultCallback;

return $this;
}

/**
* @return callable|string|null
*/
Expand Down Expand Up @@ -547,7 +579,7 @@ public function label($label)
public function serializeToValue($request)
{
return [
$this->label ?? $this->attribute => $this->value ?? $this->resolveDefaultValue($request),
$this->label ?? $this->attribute => $this->value ?? $this->resolveDefaultValue($request),
];
}

Expand All @@ -563,6 +595,7 @@ public function default($callback)
return $this;
}


/**
* Resolve the default value for the field.
*
Expand Down

0 comments on commit a2c7abd

Please sign in to comment.