8 January, 2021
Лже Артемий
Settings helpers trait

Fill fields with default values if field is currently empty.

trait SettingsDefaultAutoFill
{

public function fillDefaultIfEmpty()
{
foreach ($this->getFieldConfig()->fields as $field=>$config) {
$this->setDefaultFieldValue($field, $config);
}
foreach ($this->getFieldConfig()->tabs['fields'] as $field=>$config) {
$this->setDefaultFieldValue($field, $config);
}
}

public function setDefaultFieldValue($field, $config)
{
$fields_allowed = ['text', 'textarea', 'richeditor', 'number'];

$type = $config['type'] ?? 'text';

if (!self::get($field) && isset($config['default']) && in_array($type, $fields_allowed)) {
self::set($field, $config['default']);
}
}

public static function insertConfigFields($fields, $field_insert_after, $config_insert)
{
$i = 0;

foreach ($fields as $field=>$field_config) {
$i++;
if ($field == $field_insert_after) {
break;
}
}

$fields = array_slice($fields, 0, $i, true) +
$config_insert +
array_slice($fields, $i, count($fields)-$i, true);

return $fields;
}
}


To use autofill add this code in your Settings model:

public function beforeSave()
{
$this->fillDefaultIfEmpty();
}


Example insertng fields config:

Event::listen('system.extendConfigFile', function ($path, $config) {
if ($path === '/plugins/author/plugin/models/settings/fields.yaml') {
$config_insert = [
'field_name_to_insert_after' => [
'btn_name' => [
'label' => 'Button name',
'span' => 'auto',
'tab' => 'Tab 1',
'default' => 'Start',
],
]
];

$fields = $config['tabs']['fields'];

foreach ($config_insert as $insert_after=>$config_insert_item) {
$fields = Settings::insertConfigFields(
$fields,
$insert_after,
$config_insert_item
);
}

$config['tabs']['fields'] = $fields;

return $config;
}
});
Views: 183