In Drupal 8, Variable_set() and Variable_get() have been deprecated and variables are managed using the config table, replacing the old variables table from Drupal 7.
Configure default variables in Drupal 8/9 by using the following points,
- Create the MODULE.settings.yml file, it allows us to set default values.
- Create the MODULE.schema.yml, it defines the storage type.
This blog explains the basic example of a variable configuration in Drupal 8/9:
Create the MODULE.settings.yml file:
MODULE/config/install/MODULE.settings.yml is where the setting file should be placed.
variable_one: 'Sample Content'
variable_two: 20
variable_three: true
Create the MODULE.schema.yml file:
MODULE/config/schema/MODULE.schema.yml as the schema. Two different configurations exist. schema config_entity for entities and config_object for global configuration.
module_name.settings:
type: mapping
label: Variable Settings of My Module
mapping:
variable_one:
type: string
variable_two:
type: integer
variable_three:
type: boolean
Get the configured objects:
We can obtain configured variables by using the get() method in Drupal 8 and Drupal 9.
<?php
$get_variable_one = \Drupal::config('module_name.settings')->get('variable_one');
echo $get_variable_one; // output: Sample Content
$get_variable_two = \Drupal::config('module_name.settings')->get('variable_two');
echo $get_variable_two; // output: 20
$get_variable_three = \Drupal::config('module_name.settings')->get('variable_three');
echo $get_variable_three; // output: 1
Edit the configured objects:
We can edit configured variable values by using getEditable() function with the set() method in Drupal 8 and Drupal 9.
<?php
$config = \Drupal::service('config.factory')->getEditable('module_name.settings');
$config->set('variable_one', 'New Value')->set('variable_two', FALSE)->save();
Delete the configured objects:
In Drupal 8 and 9, there are 4 ways to delete a configuration item.
-
Using Drush
$drush config-delete "module_name.settings"
-
Using Drupal Console
$drupal config:delete active "module_name.settings"
-
Using Devel module
-
Enable the Devel module, go to the /devel/php page or used in any module and execute this:
<?php \Drupal::configFactory()->getEditable('module_name.settings')->delete();
-
-
Using Config Delete module
- Install and enable the config_delete module, then select what you wish to remove by navigating to Configuration -> Development -> Configuration synchronisation -> Delete, then click the Delete button.
Comments