nova-settings icon indicating copy to clipboard operation
nova-settings copied to clipboard

settings() default value use is inconsistent

Open k8n opened this issue 1 year ago • 0 comments

If the settings model for the following call does not exist, the default value is returned as expected:

settings('app', 'some_value', 5000) // returns 5000

When the setting model does exist and was not initialized (i.e. settings column is null), the expected result is returned:

settings('app', 'some_value', 5000) // returns 5000

However, if the settings model exists, was initialized (edited and saved in Nova), but the key 'some_value' value was not set / left blank (i.e. 'settings' column contains { some_value: null }, the unexpected value is returned:

settings('app', 'some_value', 5000) // returns null

Given the following settings class declaration, one would assume that the default value would be written to the database if not explicitly provided in Nova, but that does not happen. I work around the issue using fillUsing() for now:

class ApplicationSettings extends AbstractType
{
    public function fields(): array
    {
        return [
            Currency::make('Some Value', 'some_value')
                ->default(5000),
                // ->default(fn () => 5000) // also no effect
                // Workaround
                ->fillUsing(function (NovaRequest $request, $model, $attribute) {
                    // if the key exists in the input with null value (and it does when the field is left blank),
                    // the null value is returned; default is not at play
                    $value = $request->input($attribute, 5000) ?? 5000;
                    $model->forceFill([Str::replace('.', '->', $attribute) => $value]);
                })
        ];
    }
}

I'm not sure how this issue can be handled.

Perhaps settings() helper could return the default value if the requested setting resolves to null?

https://github.com/stepanenko3/nova-settings/blob/1b048348b71ee388cf22ef814a243a3b21488cad/src/helpers.php#L49-L53

k8n avatar Oct 24 '24 18:10 k8n