[Drupal-8] Article about how to Configure Variables in Drupal 8?
In Drupal 8, variable_set()
and variable_get()
is deprecated. The variables database table in Drupal 7 is now removed in Drupal 8, and is replaced with config table. We can create a variable while installing the module using MODULE.setting.yml and MODULE.schema.yml files.
We can configure default values in MODULE.setting.yml file and the storage type will be defined in MODULE.schema.yml. The setting file should be stored as MODULE/config/install/MODULE.setting.yml and the schema as MODULE/config/schema/MODULE.schema.yml. There are two types of configuration schema config_object
for global configuration and config_entity
for entities.
Simple example for variable configuration in Drupal 8 is as follows:
MODULE.schema.yml
mymodule.settings:
type: mapping
label: Variable Settings of My Module
mapping:
variable_one:
type: string
variable_two:
type: email
variable_three:
type: boolean
MODULE.settings.yml
variable_one: 'Sample Content'
variable_two: ''
variable_three: true
We can get the configured objects as:
$config = \Drupal::config('mymodule.settings');
$variable_one = $config->get('variable_one');
We can edit the configuration as,
$config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
$config->set('variable_one', 'New Value')
->set('variable_two', FALSE)
->save();
Hope you find this article useful. Also, if any queries please feel free to get in touch with us.