From b15e3f6410bfb289ab5e05a3ccf39c45b6a4388d Mon Sep 17 00:00:00 2001 From: Lupacescu Eduard Date: Wed, 4 Dec 2024 17:18:16 +0200 Subject: [PATCH] 9.6.0 (#619) * feat: support string url as path for files * Fix styling * fix: fixing str * feat: add defaultCallback method * Fix styling * fix: docs * Fix styling --------- Co-authored-by: binaryk --- docs-v2/content/en/api/fields.md | 12 ++++++++++ src/Fields/Field.php | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/docs-v2/content/en/api/fields.md b/docs-v2/content/en/api/fields.md index 994c7141..bf6da1ec 100644 --- a/docs-v2/content/en/api/fields.md +++ b/docs-v2/content/en/api/fields.md @@ -369,6 +369,18 @@ Now, for the fields that don't have a description into the database, it will ret The default value is ONLY used for the READ, not for WRITE requests. +### Default Stored Value + +During any (update or store requests), this is called after the fill and store callbacks. + +You can pass a callable or a value, and it will be attached to the model if no value provided otherwise. + +Imagine it's like `attributes` in the model: + +```php +field('currency')->defaultCallback('EUR'), +``` + ## Customizations ### Field label diff --git a/src/Fields/Field.php b/src/Fields/Field.php index 5e128a56..7137df4c 100644 --- a/src/Fields/Field.php +++ b/src/Fields/Field.php @@ -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. */ @@ -205,6 +207,22 @@ public function fillCallback(callable|Closure $callback) return $this; } + /** + * This is called after the fill and store callbacks. + * + * You can pass a callable or a value, and it will be attached to the model if no value provided otherwise. + * + * Imagine it's like `attributes` in the model. + * + * @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. * @@ -246,6 +264,12 @@ public function fillAttribute(RestifyRequest $request, $model, ?int $bulkRow = n $bulkRow ); + $this->fillAttributeFromDefault( + $request, + $model, + $this->label ?? $this->attribute + ); + $this->fillAttributeFromValue( $request, $model, @@ -310,6 +334,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 */