Add a Default Configuration

Last updated on
19 December 2021

By adding a single settings yaml file to our module, Drupal will automatically load the contents of that yaml file, and we can access it to provide a default configuration. From the root folder of our module, create a new folder and name it 'config'. Inside the new folder, create another folder and name it 'install'. Finally, inside config/install create a new file and call it hello_world.settings.yml.

hello:
  name: 'Hank Williams'

Remember that yaml is whitespace sensitive. To make use of the value loaded into the Drupal object, however, we will need to add this method to our HelloBlock class (see the Creating Custom Blocks tutorial):

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_config = \Drupal::config('hello_world.settings');
    return [
      'hello_block_name' => $default_config->get('hello.name'),
    ];
  }

This value will be used when the module is installed. So to verify, uninstall and install your module. And when you add your block again to a region, you should see the default value.

Find more information on simple configuration (\Drupal::config).

Help improve this page

Page status: No known problems

You can: