Skip to content

Commit a2c7abd

Browse files
committed
feat: add defaultCallback method
1 parent 2da856d commit a2c7abd

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/Fields/Field.php

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ class Field extends OrganicField implements JsonSerializable
115115
*/
116116
protected $valueCallback;
117117

118+
protected $fillDefaultCallback;
119+
118120
/**
119121
* Closure be used to be called after the field value stored.
120122
*/
@@ -205,6 +207,13 @@ public function fillCallback(callable|Closure $callback)
205207
return $this;
206208
}
207209

210+
public function defaultCallback(mixed $callback)
211+
{
212+
$this->defaultCallback = $callback;
213+
214+
return $this;
215+
}
216+
208217
/**
209218
* Fill attribute with value from the request or delegate this action to the user defined callback.
210219
*
@@ -246,6 +255,12 @@ public function fillAttribute(RestifyRequest $request, $model, ?int $bulkRow = n
246255
$bulkRow
247256
);
248257

258+
$this->fillAttributeFromDefault(
259+
$request,
260+
$model,
261+
$this->label ?? $this->attribute
262+
);
263+
249264
$this->fillAttributeFromValue(
250265
$request,
251266
$model,
@@ -310,6 +325,23 @@ protected function fillAttributeFromValue(RestifyRequest $request, $model, $attr
310325
return $this;
311326
}
312327

328+
protected function fillAttributeFromDefault(RestifyRequest $request, $model, $attribute)
329+
{
330+
if ($model->{$attribute}) {
331+
return $this;
332+
}
333+
334+
if (! isset($this->fillDefaultCallback)) {
335+
return $this;
336+
}
337+
338+
$model->{$attribute} = is_callable($this->fillDefaultCallback)
339+
? call_user_func($this->fillDefaultCallback, $request, $model, $attribute)
340+
: $this->fillDefaultCallback;
341+
342+
return $this;
343+
}
344+
313345
/**
314346
* @return callable|string|null
315347
*/
@@ -547,7 +579,7 @@ public function label($label)
547579
public function serializeToValue($request)
548580
{
549581
return [
550-
$this->label ?? $this->attribute => $this->value ?? $this->resolveDefaultValue($request),
582+
$this->label ?? $this->attribute => $this->value ?? $this->resolveDefaultValue($request),
551583
];
552584
}
553585

@@ -563,6 +595,7 @@ public function default($callback)
563595
return $this;
564596
}
565597

598+
566599
/**
567600
* Resolve the default value for the field.
568601
*

0 commit comments

Comments
 (0)