Help Drupal help your configuration
James Williams
TL;DR: Define a schema for any bespoke configuration, it's not too hard. It's needed to make it translatable, but Drupal 8 will also validate your config against it so it's still handy on non-translatable sites. As a schema ensures your configuration is valid, your code, or Drupal itself, can trip up without one.
Recently I updated a simple configuration setting via some PHP code, and Drupal immediately threw up an obscure error. It turned out to be because the custom setting that I updated didn't have a configuration schema.
Schemas are used to instruct Drupal 8 what format every piece of a configuration object should be in. For example: text, integers, an array mapping, etc. That means they can be used to validate configuration, keeping your code and Drupal's handling of the settings robust and predictable. It also allows the configuration to be translated, but that wasn't on my radar for this particular project.
If you're aware of the variable module for Drupal 7, then you can think of configuration schemas as the equivalent of hook_variable_info()
, but written in YAML.
Here's an example of the sort of thing that's needed, to go in my_module/config/schema/my_module.schema.yml
:
my_module.settings:
type: config_object
label: 'My custom settings'
mapping:
message:
type: text
label: 'Message to display on page XYZ'
some_setting:
type: 'integer'
label: 'Behave differently when this is 0, 1, or 2'
The pragmatic reality is that you may well get away fine without giving your configuration a schema. But you may also run into obscure issues like I did without one, which are very hard to understand. I could get around the problem by skipping the validation by passing the 'has_trusted_data' parameter to my $config->save()
call as TRUE
. Clearing caches may also resolve your problem.
But ultimately, those workarounds just plaster over the cracks. Set up a schema and you avoid those problems, and get robust validation for free. Hopefully my example YAML above shows how it can be quite simple to do.
As a bonus, PhpStorm can even give you autocomplete suggestions for configuration names that have a schema defined for them, when typing \Drupal::config('...
!