Very often we need to write some data into the variable, which we can replace at any moment of use. There are two such functions in Drupal 7: variable_get() and variable_set(). In Drupal 8 we have State API and Configuration API for these purposes. In this article, you’ll familiarize with their use and also tell the difference between them.
State API should be used bypassing configuration only when your goals of use meet the following requirements:
- This API will be used for storage of some system information;
- You are not going to transfer the setup data from server to server because the data won’t be saved in case of exporting configuration;
- These data won’t be edited by the user through the interface.
A good example of State API use is storing the timestamp of the last cron operation run.
State API: Writing Values
For entry, we should use a pair: a key and a value.
For multiple entries we use the following code:
// $values - array with the couple of key and value. $values = [ 'key1' => 'value1', 'key2' => 'value2' ]; Drupal::state()->setMultiple($values);
State API: Getting Data
Getting one value with a key.
$val = Drupal::state()->get(‘key’);
Getting several values:
$keys = [ 'key', 'key2' ]; $pairs = Drupal::state()->getMultiple($keys).// $values - array with the couple of key and value. $values = [ 'key1' => 'value1', 'key2' => 'value2' ]; Drupal::state()->setMultiple($values);
State API: Deleting Data
Deletig is accessible only with one value:
When you use Configuration API, setup data will be saved. If you export the website configuration, you’ll find name.settings.yml file with the following content key value.
Configuration API: Creating the Configuration Object
$config = Drupal::config(‘name.settings'); Configuration API: Writting values. $config->set('key','value'); $config->save(); Configuration API: ????????? ??????. $config->get('key'); // value. Configuration API: Deleting data. $config->delete('key'); $config->save();
Now if you export the website configuration, you’ll find name.settings.yml file with the following content key value.
Hope that this quick tip was useful for you! if you don’t want to spend your time on all these works, just let us know and we’ll do all necessary works on Drupal development for you. Leave your contacts in “Ask Questions” form below, and we’ll get acquainted for an interesting discussion. Wish you good luck and friendship with Drupal.