outl1ne / nova-settings

A Laravel Nova tool for editing custom settings using native Nova fields.
MIT License
278 stars 97 forks source link

Field default value not working #145

Closed Dartui closed 2 years ago

Dartui commented 2 years ago

Hi, I am trying to define default value for field but it is not working. I've tested this only on Boolean and Text field without any success.

Example code:


use Outl1ne\NovaSettings\NovaSettings;
use Laravel\Nova\Fields\Text;

NovaSettings::addSettingsFields([
    Text::make('Test', 'test')->default(fn() => 'default value'),
    Text::make('Another test', 'another_test')->default('default value'),
]);

Docs about default values: https://nova.laravel.com/docs/4.0/resources/fields.html#default-values

Tarpsvo commented 2 years ago

Insert your default value into the database instead. I don't think it's okay to show a setting having a value when in reality it's not in the database. ;)

Dartui commented 2 years ago

I am trying to add setting for something that was enabled by hardcoded value in code. Now if I add Boolean field to settings and someone just click save it will store false value in database rather than true, thus this option will be disabled.

To be more I am developing something that is shipped as package and I cannot be 100% sure that someone will migrate default value to the database.

Dartui commented 2 years ago

If anyone ever stumble upon similar issue then "default" method behavior can be reproduced using third parameter (resolve callback) of field:

NovaSettings::addSettingsFields([
    Boolean::make('Test', 'test_setting', fn() => $this->resolveTestSettingValue()),
]);

public function resolveTestSettingValue(): bool
{
    $value = NovaSettings::getSetting('test_setting', null);

    return $value !== null ? boolval($value) : true; // true is the default value
}
chrisbjr commented 1 year ago

Very useful @Dartui this works

Number::make('Notifications Duration', 'notifications_duration', function () {
    return NovaSettings::getSetting('notifications_duration', 8000);
}),