Categories

(104)
(49)
(66)
(16)

Configuration in Drupal 8: tips and examples for developers

27.10.2015
Configuration in Drupal 8: tips and examples for developers
Author:

Embed the presentation code:

<iframe src="https://prezi.com/3m8yspw-7cwx/configuration-in-drupal-8/" width="100%"></iframe> <p>Source: <a href="http://internetdevels.com/blog/configuration-in-drupal-8">InternetDevels.com</a></p>

In one of the recent blog posts by our developer, we offered you
Drupal 8 development tips. Today, we'll discuss working with configuration in
Drupal 8. Real profit for Drupal developers by the same author. Enjoy! ;)

Drupal 8 offers a new configuration data saving system. It is useful for Drupal developers because it facilitates configuration import and export.

The configuration by default comes with modules and themes and is saved in YAML files (eg: image.settings.yml), and when the module or the theme is enabled, the configuration is imported to the active configuration repository. By default, the active configuration is saved in the database. The Drupal 8 core includes the Configuration Manager module.

The Drupal 8 Configuration Manager module

This module provides us with a user interface for configuration changes import and export. Configuration Manager makes it possible to deploy configuration from one environment in another - provided that it is the same site. The site is identified with the help of a universally unique identifier (UUID). The Configuration Manager module eliminates the need for additional modules such as Features and Strongarm.

In Drupal 7, to move content type etc., you had to download Features, make settings, and now you just need to paste the copied configuration to get the required content type.

Configuration Manager enables you to:

  • synchronize configuration;
  • make one-time import/export;
  • make full import/export.

Making configuration changes on a live site is not the best idea. The aim of the configuration system in Drupal 8 is to enable you to make various settings on your test site and move only the ready settings to your live site.

The Configuration Manager page can be found here Manage > Configuration > Development > Configuration management або admin/config/development/configuration.

Configuration import and export in Drupal 8

For one-time export form test to live site you need to do the following:

  • select the Export tab (1);
  • select the configuration type (2);
  • select the required configuration (3);
  • copy the configuration text (4)

Configuration in Drupal 8

For one-time export of the previously imported configuration, you need to do the following:

  • select the Import tab (1);
  • select the configuration type (2);
  • paste the configuration text (3);
  • press the Import button (4).

Configuration in Drupal 8

For full configuration export, you need to select the “Full Import/Export”(1) tab, then the “Export”(2) tab. After that you just need to press the Export(3) button. After these actions, the uploading of the archive with the configuration will begin in the browser.

Configuration in Drupal 8

To import the newly uploaded configuration, you need to do the following:

  • select the “Full Import/Export”(1) tab
  • select the “Export”(2) tab
  • select the archive file(3) and press the Upload(4) button

Configuration in Drupal 8

By default, Drupal 8 saves configuration files in these folders:

  • 'sites/default/files/config/active'
  • 'sites/default/files/config/staging'

You can change the configuration saving place in the settings.php file. To do this, you need to go to

$config_directories['active'] = ‘your_path’ та $config_directories['active'] = ‘your_path’ and specify the required path.

Drupal 8 provides us with a powerful API to work with configuration via the code.

On the next step, I will show how to programmatically create, modify, and delete the settings.

Examples of working with configuration in Drupal 8

Now let’s consider working with configuration on our example module.

In Drupal 7, one of the most common ways to save the settings was using variable_get() and variable_set(). In Drupal 8, they are replaced with a new configuration system. The variable_get()/variable_set() functions were removed from Drupal 8. You should work with the settings in the following way:

$config = \Drupal::configFactory()->getEditable($key) - getting the necessary configuration.

$configuration->set($key , $value ) - setting the necessary value.

$configuration->save() - saving the changes.

The module settings by default can be saved in the module_name.settings.yml file that should be placed in the following folder:

config/install.

To set a dynamic value by default that can not be written in the your_module_name.settings.yml file, you should use hook_install(). For example:

<?php
/**
* Implements hook_install().
*/
function idevels_config_example_install() {
// Set default values for config which require dynamic values.
\Drupal::configFactory()->getEditable('idevels_config_example.settings') ->set('some_data2', \Drupal::configFactory()->getEditable('system.site')->get('name'))
->save();
}
?>

This code sets the site name as a value for the some_data2 field. Let's consider this example in more detail. With the help of line (7), we get an object with all the necessary settings, in line (8) we set the site name in the some_data2 field and finally save our settings.

In Drupal 7, the system_settings_form() function was used for module configuration form creation. In Drupal 8, configuration forms are created as follows:

 <?php

/**
* @file
* Contains \Drupal\demo\Form\DemoForm.
*/

namespace Drupal\idevels_config_example\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\ConfigFactory;

class TestConfForm extends ConfigFormBase {
public function getFormId() {
return 'example_set_form';
}

/**
* @param array $form
* @param FormStateInterface $form_state
* @return array
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('idevels_config_example.settings');
$form['custom_field'] = [
'#type' => 'textfield',
'#title' => $this->t('Some text data'),
'#default_value' => $config->get('some_data2'),
];
$form['custom_field2'] = [
'#type' => 'textfield',
'#title' => $this->t('Some text data'),
'#default_value' => $config->get('some_data'),
];

return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
$config = \Drupal::configFactory()->getEditable('idevels_config_example.settings')
->set('some_data2', $form_state->getValue('custom_field'))
->set('some_data', $form_state->getValue('custom_field2'))
->save();

parent::submitForm($form, $form_state);
}

/**
* Gets the configuration names that will be editable.
*
* @return array
* An array of configuration object names that are editable if called in
* conjunction with the trait's config() method.
*/
protected function getEditableConfigNames()
{
return ['idevels_config_example.settings'];
}
}

It should be noted that your form class inheritance should be made from the ConfigFormBase class, not the FormBase, as in most forms. That’s how the created form looks:

Configuration in Drupal 8

It is worth noting that, at the moment, in the second field, the default values are data from the configuration file idevels_config_example.settings.yml, while in the first one it’s the site name which we get in hook_install().

Here is how the content of the idevels_config_example.settings.yml file looks:

some_data: 'default data'

To create your content type in the module, you need to create the necessary YAML files in the your_module/config/install folder. For example, to create the type of content "my_content_type" which will have one “body” field, you need to create the following files:

 core.entity_form_display.node.my_content_type.default.yml:
uuid: 0e54b601-1c72-4989-8900-b34fc31c7721
langcode: en
status: true
dependencies:
config:
- field.field.node.my_content_type.body
- node.type.my_content_type
module:
- entity_reference
- path
- text
id: node.my_content_type.default
targetEntityType: node
bundle: my_content_type
mode: default
content:
title:
type: string_textfield
weight: 0
settings:
size: 60
placeholder: ''
third_party_settings: { }
uid:
type: entity_reference_autocomplete
weight: 1
settings:
match_operator: CONTAINS
size: 60
placeholder: ''
third_party_settings: { }
created:
type: datetime_timestamp
weight: 2
settings: { }
third_party_settings: { }
promote:
type: boolean_checkbox
weight: 3
settings:
display_label: true
third_party_settings: { }
sticky:
type: boolean_checkbox
weight: 4
settings:
display_label: true
third_party_settings: { }
path:
type: path
weight: 5
settings: { }
third_party_settings: { }
body:
type: text_textarea_with_summary
weight: 6
settings:
rows: 9
summary_rows: 3
placeholder: ''
third_party_settings: { }
hidden: { }
third_party_settings: { }

 field.field.node.my_content_type.body.yml:
uuid: d0bf6e80-a1e7-4139-b446-70338272f3c9
langcode: en
status: true
dependencies:
config:
- field.storage.node.body
- node.type.my_content_type
module:
- text
id: node.my_content_type.body
field_name: body
entity_type: node
bundle: my_content_type
label: FieldBody
description: ''
required: false
translatable: true
default_value: { }
default_value_callback: ''
settings:
display_summary: true
third_party_settings: { }
field_type: text_with_summary

 node.type.my_content_type.yml:
uuid: f07bfea6-da48-49c9-bb32-500f4ecc1c37
langcode: en
status: true
dependencies: { }
name: 'My Content Type'
type: my_content_type
description: 'custom content type.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true
third_party_settings: { }

Now, with the module installation, a new content type will be created the settings for which are described in the above-mentioned files. Changes in configuration of the newly created type of content can be moved between sites with the Configuration management module the work of which is described above.

In my opinion, Drupal 8 has a very convenient configuration system that makes it possible to do without third-party modules.

4 votes, Rating: 5

Read also

1

SASS and LESS preprocessors make front-end development much easier. To compile them to CSS...

2

If you want to begin studying Symfony web development, this Symfony2 framework tutorial by our developer could...

3

Hello, everyone! The release of Drupal 8 is almost here, but its beta version is available for use now....

4

In Symfony, there are many console commands to help you in your work. In this article we consider the most frequently used Symfony commands.The tutorial should be very useful for those who are...

5

Happy Tester’s Day to everyone! :) Check out the new blog post on QA testing in BrowserStack from InternetDevels Company...

Need a quote? Let's discuss the project

Are you looking for someone to help you with your Drupal Web Development needs? Let’s get in touch and discuss the requirements of your project. We would love to hear from you.

Join the people who have already subscribed!

Want to be aware of important and interesting things happening? We will inform you about new blog posts on Drupal development, design, QA testing and more, as well news about Drupal events.

No charge. Unsubscribe anytime