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:
$this
is the admin settings form class.->
is an object operatorconfig('welcome.adminsettings’)
:welcome.adminsettings
is the name of the module’s configuration.->set('welcome_message', $form_state->getValue('welcome_message’))
: here it is setting ‘welcome_message’ and get the values from the form state.->save:
save the form data.
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.
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:
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.