My plugin uses a {{ forms.editableTable({...}) }}
field within the settings.twig. When the field has row items it will save just fine, but when the table is empty it attempts to save it as an empty string. This throws an error:
Typed property marknotton\myplugin\models\Settings::$whitelist must be array, string used
I would have expected it to save an empty array. Especially as I've defined the default value as an array in the Settings class.
Following Brandons suggestion from an older issue, I have tried to amend the setting before it is saved via an Event listener:
// This is in my plugins init() method
Event::on(
MyPlugin::class,
MyPlugin::EVENT_BEFORE_SAVE_SETTINGS,
[Settings::class, 'onBeforeSaveSettings']
);
class Settings extends Model {
public array $whitelist = [];
public function rules(): array
{
return [
['whitelist', ArrayValidator::class],
];
}
public static function onBeforeSaveSettings(ModelEvent $event): ModelEvent
{
$plugin = $event->sender;
$settings = $plugin->getSettings();
if ( is_string($settings['whitelist']) ) {
$settings['whitelist'] = [];
}
return $event;
}
}
This works perfectly in Craft 4, but in Craft 3 my 'onBeforeSaveSettings' method isn't getting called at all.
Is this just a novice data type issue I'm overlooking? Or is the EVENT_BEFORE_SAVE_SETTINGS
event failing to run on Craft 3 specifically?