Skip to main content

Help Drupal help your configuration

An article from ComputerMinds - Building with Drupal in the UK since 2005
20th Jun 2017

James Williams

Senior Developer
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?

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:

  type: config_object
  label: 'My custom settings'
      type: text
      label: 'Message to display on page XYZ'
      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('...!

Hi, thanks for reading

ComputerMinds are the UK’s Drupal specialists with offices in Bristol and Coventry. We offer a range of Drupal services including Consultancy, Development, Training and Support. Whatever your Drupal problem, we can help.