Add configuration for default values
By adding a single YAML settings file to our module, Drupal will automatically load the contents of this YAML file, and we’ll be able to access it to provide default configuration. From the root folder of your module, create a new folder called “config.” Inside that folder, create another one named “install.” Finally, inside config/install, create a new file and name it hello_world.settings.yml.
hello: name: 'Hank Williams'
Remember, YAML is whitespace-sensitive. However, to actually use the value loaded into a Drupal object, we 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 test it, uninstall and reinstall your module. And when you add your block to a region again, you should see the default value appear.
Find more information about the Simple Configuration API (\Drupal::config).
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.