Last updated May 25, 2016. Created on September 17, 2012.
Edited by Wim Leers, HongPong, targoo, benjy. Log in to edit this page.

The State API provides a place for developers to store information about the system's state. State information differs from configuration in the following ways:

  • It is specific to an individual environment.
  • You will never want to deploy it between environments.
  • You can reset a system, losing all state. Its configuration remains.
  • So, use State API to store transient information, that is okay to lose after a reset. Think: CSRF tokens, tracking when something non-critical last happened …

A good example of state is the last time cron was run. This is specific to an environment and has no use in deployment. The state API is a simple system to store this information, which previously would have been stored in the variables system.

Typical usage:

  • Get a value:
    $val = \Drupal::state()->get('key');

  • Get multiple key/value pairs:
    $pairs = \Drupal::state()->getMultiple($keys);

  • Set a value:

  • Set multiple values:

  • Delete a value:

Data which needs to be edited by humans or needs to be shared between environments should use \Drupal::config() instead. See the Configuration API info.

Looking for support? Visit the forums, or join #drupal-support in IRC.


tedbow’s picture

Can state not used for thing that is "edited by humans"? Even if it satisfies the other conditions?

iainH’s picture

Presumably there is a key that indicates when a D8 site is in maintenance mode. Where does one look for what that key might be?

To use drush sget you need to know what the key is.

OK, you can look through Drupal core code and you'll find that you need to say drush @mysite sget system.maintenance_mode ... I couldn't find a page in the API docs that listed state keys. How would one set about building such a page?

moshe weitzman’s picture

Drupal has no registry of such keys. All you can do right now is grep/search.

incursus’s picture

If you have the Drupal CLI installed, you can just type:

drupal state:debug

.. to get a list of all the state keys :)