Ad

Setting A Default Value On Settings Form Return Null In Octobercms

I create a little plugin for the OctoberCMS but now dealing with a problem of setting a default value for a settings form.

I used database storage for my plugin settings (Backend -> Settings tab -> My Plugin tab) which works , quite good, except I cannot set default values.

I have a fields.yaml with this content:

tabs:
    fields:
        reviews_border_color:
            label: 'Field1'
            span: left
            tab: 'review_sticker'
            required: 1
            type: text
            default: '#F2F2F2'
        rating_star_size:
            label: 'Field2'
            span: left
            tab: 'review_sticker'
            required: 1
            type: number
            default: 14

I retrieve the settings in my components like this:

<?php namespace Codedge\TestPlugin\Components;

use Cms\Classes\ComponentBase;
use Codedge\TestPlugin\Models\Settings;

class TestComponent extends ComponentBase
{
    public $starSize;
    public $borderColor;

    public function componentDetails()
    {
        return [
            'name'        => 'Test Component',
            'description' => '...'
        ];
    }

    public function defineProperties()
    {
        return [];
    }

    public function init()
    {
        $this->starSize = Settings::get('rating_star_size'); // not giving a default value when empty, default is 14
        $this->borderColor = Settings::get('reviews_border_color'); // not giving a default value when empty, default is '#F2F2F2'
    }

}

I also tried to set the default value, as second param in the get() method as suggested in the OctoberCMS docs:

public function init()
{
    $this->starSize = Settings::get('rating_star_size', 14); // returns null
    $this->borderColor = Settings::get('reviews_border_color', '#F2F2F2'); // returns null
}

So any suggestions how I can reliably set a default value if none is specified/entered in to the settings form field?

Update:

After some digging aroung I found the explanation in the method getSettingsValue() in system/behaviors/SettingsModel.php

/**
 * Get a single setting value, or return a default value
 */
public function getSettingsValue($key, $default = null)
{
    if (array_key_exists($key, $this->fieldValues)) {
        return $this->fieldValues[$key];
    }

    return $default;
}

As my field exists in $this->fieldValues it returns it empty to me instead of returning the $default value.

So what I thought, returning the default value if the field value is empty, is not covered.

Any suggestions?

Ad

Answer

After consulting with the OctoberCMS team on Github, the current behaviour is intented/not a bug - see https://github.com/octobercms/october/issues/2094 . There could be considerations to change this behaviour, but this is another story.

Ad
source: stackoverflow.com
Ad