diff --git a/src/Fields/Field.php b/src/Fields/Field.php index f007a8c1..3f8ab8b5 100644 --- a/src/Fields/Field.php +++ b/src/Fields/Field.php @@ -41,6 +41,11 @@ abstract class Field implements Arrayable, JsonSerializable */ protected ?Closure $formatResolver = null; + /** + * The default value resolver callback. + */ + protected ?Closure $defaultValueResolver = null; + /** * The value resolver callback. */ @@ -342,6 +347,20 @@ public function resolveSearchQuery(Request $request, Builder $query, mixed $valu : call_user_func_array($this->searchQueryResolver, [$request, $query, $value]); } + /** + * Set the default value resolver. + */ + public function default(mixed $value): static + { + if (! $value instanceof Closure) { + $value = fn (): mixed => $value; + } + + $this->defaultValueResolver = $value; + + return $this; + } + /** * Set the value resolver. */ @@ -363,6 +382,10 @@ public function resolveValue(Request $request, Model $model): mixed $value = $this->getValue($model); + if (! is_null($this->defaultValueResolver)) { + $value = call_user_func_array($this->defaultValueResolver, [$request, $model]); + } + if (is_null($this->valueResolver)) { return $value; }