Blair Wadman 3 minute read

Saving Drupal 8 module configuration - where do we save the data?

A reader asked me: “we save the data, but where did we save it?”. He was referring to my tutorial on creating an admin form in Drupal 8.

This tutorial is great and helped me make a big step in learning to make modules. I have a question though, we save the data, but where did we save it?

This is the code in question:

  /**  
   * {@inheritdoc}  
   */  
  public function submitForm(array &$form, FormStateInterface $form_state) {  
    parent::submitForm($form, $form_state);  

    $this->config('welcome.adminsettings')  
      ->set('welcome_message', $form_state->getValue('welcome_message'))  
      ->save();  
  }

The submitForm() method is responsible for saving the form data when the form is submitted. Take a look at the code inside the method:

    $this->config('welcome.adminsettings')
      ->set('welcome_message', $form_state->getValue('welcome_message'))
      ->save();

Let’s break this down line by line:

And that is all you need to save config data like this. Drupal will automatically save this to the config table in the database.

If you search for the name welcome.adminsettings in the config table of your Drupal sites database, you will find the entry.

Configuration table in Drupal 8

Open the data in the config table:

a:3:{s:7:"welcome";a:1:{s:15:"welcome_message";s:19:"Welcome to the site";}s:5:"_core";a:1:{s:19:"default_config_hash";s:43:"1YWRehpQ5QLV9nBN1B6d_98e8ocmTLRyjHF16oJk_9Q";}s:15:"welcome_message";s:20:"Welcome to the site!";}

And have a look at the admin form:

Admin settings forms

You can see that this contains the very same message ("Welcome to the site!”).

Get the config value with Drush

An easy way to test the config value that is stored is to use the Drush config-get command.

drush config-get welcome.adminsettings

This will return:

welcome:
  welcome_message: 'Welcome to the site'
_core:
  default_config_hash: 1YWRehpQ5QLV9nBN1B6d_98e8ocmTLRyjHF16oJk_9Q
welcome_message: 'Welcome to the site!'

As you can see, this matches the value in the form.

The admin form example is from my book, Conquer Drupal 8 Module Development, which has helped hundreds of people build their first working Drupal 8 module.