Drupal Configuration System (Config API) | Drupal 8

Drupal Configuration System (Config API)

Submitted by editor on Wed, 06/07/2017 - 11:05

How to use Drupal 8 config API (The configuration system)?

Drupal 8 embedded with a configuration system which allow users to store variables in the database and usable in site wide as variables in drupal 7. Intend of use variable_set variable_get variable_del, in drupal 8 use Configuration API. Drupal provide 2 methods to use configuration in Readable and Writable mode.
To write/edit (as variable_set and variable_del) a configuration:  \Drupal::configFactory()->getEditable('THE-CONFIG-NAME')
To read (as variable_get) a config : \Drupal::config('THE-CONFIG-NAME')

Editable mode (Can also read).

$config = \Drupal::configFactory()->getEditable('my_config_name.config'); // Get config object.
$config->set('test_key','test_value'); // Set value.
$config->save(); // Save configuration.
// Few other operations.
$config->delete(); // Delete the configuration object.
$config->clear('test_key'); // Clear a value.
$config->merge($data_array); // Merge values.
$value = $config->get('test_key'); // Read a value.
$config->save(); // Save configuration.

Readable mode.

$config = \Drupal::config('my_config_name.config');
$value = $config->get('test_key');

Note: Using a correct naming convention avoid conflicts between modules. It is recommended to use configuration name like:
Example: mymodule.settings


Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.