6

I have some code in Drupal 7 what are using variable_get. Now I would like to write the code in Drupal 8. So I was reading this but its didn't help me a lot.

How to write this code in Drupal 8 from code in Drupal 7?

$types = array_values(variable_get('test_content_types', array()));

or this

'#default_value' => variable_get('test_content_types', array()),

Some suggestion.

10

In Drupal 7

 $data =  variable_get('test_content_types');

In Drupal 8

 $data = \Drupal::state()->get('test_content_types'); 

For more information about about "get", "set", "delete" visit - Step 5: How to upgrade D7 variables to D8's state system.

  • Thank you @darol100 .. The link is nice.. Now I understend. So I can write $data = \Drupal::state()->get('test_content_types', array()); – SakaSerbia Jan 8 '16 at 12:43
  • 7
    Be aware that in D8 there is a difference between state and config. As noted on drupal.org/developing/api/8/configuration: "Configuration is a place to store information that you would want to synchronize from development to production. This information is often created during site building and is not typically generated by regular users during normal site operation. You should use the State API, not configuration, for storing local variables that shouldn't travel between instances. Use state for hidden system values, and if you never want to deploy it between environments." – marcvangend Jan 8 '16 at 12:47
3

The accepted answer is half the answer. As marcvangend notes, there are two options in Drupal 8 for what used to be stored in the variables table and was stored and retrieved with variable_set() and variable_get(). The first, documented in darol100's answer, is the State API.

The second is the Configuration API and should be used in most cases where you have a configuration form. It requires at minimum in your module a configuration installation file, for example config/install/example.settings.yml. For a single piece of configuration (with multiple potential values), that file could just contain for example:

test_content_types: - article

And then use the value with:

$types = \Drupal::config('example.settings')->get('test_content_types');

Or change the stored values with:

\Drupal::service('config.factory')
  ->getEditable('example.settings')
  ->set('test_content_types', ['article', 'page'])
  ->save();

See also the the Drupal 8 documentation for D7 to D8 configuration upgrades and using configuration in modules.

  • For me, this is the correct answer to the question. I'm currently making the transition from Drupal 7 and it helped me a lot. – Geat Dec 18 '18 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.