From 6c4efc044dfec9193986c15b13bfcbefff790bb1 Mon Sep 17 00:00:00 2001 From: Sami Mokaddem Date: Wed, 20 Oct 2021 12:48:13 +0200 Subject: [PATCH] fix: [settings] Make sure to save multi-select value as an array --- src/Model/Table/SettingsTable.php | 12 ++++++++++++ templates/element/Settings/field.php | 8 +++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Model/Table/SettingsTable.php b/src/Model/Table/SettingsTable.php index 0459ce7..4a2d0a6 100644 --- a/src/Model/Table/SettingsTable.php +++ b/src/Model/Table/SettingsTable.php @@ -56,6 +56,13 @@ class SettingsTable extends AppTable $errors[] = __('Invalid option provided'); } } + if ($setting['type'] == 'multi-select') { + foreach ($value as $v) { + if (!in_array($v, array_keys($setting['options']))) { + $errors[] = __('Invalid option provided'); + } + } + } if (empty($errors) && !empty($setting['beforeSave'])) { $setting['value'] = $value ?? ''; $beforeSaveResult = $this->SettingsProvider->evaluateFunctionForSetting($setting['beforeSave'], $setting); @@ -79,6 +86,11 @@ class SettingsTable extends AppTable if ($setting['type'] == 'boolean') { return (bool) $value; } + if ($setting['type'] == 'multi-select') { + if (!is_array($value)) { + $value = json_decode($value); + } + } return $value; } diff --git a/templates/element/Settings/field.php b/templates/element/Settings/field.php index 1c72d5d..34bdde8 100644 --- a/templates/element/Settings/field.php +++ b/templates/element/Settings/field.php @@ -64,7 +64,13 @@ $settingId = str_replace('.', '_', $settingName); $setting['value'] = $setting['value'] ?? ''; if ($setting['type'] == 'multi-select') { - $setting['value'] = json_decode(($setting['value'])); + if (!is_array($setting['value'])) { + $firstChar = substr($setting['value'], 0, 1); + if ($firstChar != '{' && $firstChar != '[') { // make sure to cast a simple string into an array + $setting['value'] = sprintf('["%s"]', $setting['value']); + } + $setting['value'] = json_decode($setting['value']); + } } $options = []; $options[] = $appView->Bootstrap->genNode('option', ['value' => '-1', 'data-is-empty-option' => '1'], __('Select an option'));