Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

How to set and get data with Drupal's 'tempstore' service | Example code

Parent Feed: 

If you need a temporary buffer in Drupal to save data to, Drupal's tempstore service might come in handy. We used it for example in a webshop module, where users didn't have a saved address yet and also had to option to never save their address permanently (because of gdpr).

So, after some searching, the code is pretty straight forward. This example might save you some time to implement it

We implemented this in a custom Drupal webshop service, the functions are called in other code via dependency injection. So here is how to set and get your custom data with help of Drupal's tempstore:

(Be aware: the tempstore data wíll expire automatically)

   * Set data in Drupal's temp_store.
   * @param array $vars
  public function setMyDataInTempStore(array $vars) {
    // Get tempstore service.
    $tempstore = \Drupal::service('tempstore.private');
    // Get tempstore data we need.
    $tempstore_data = $tempstore->get('my_custom_key');
    $params = $tempstore_data->get('params');
    // Fill vars.
    $params['var_1'] = $vars['var_1'];
    $params['var_2'] = $vars['var_2'];
    // Save vars to tempstore.
    $tempstore_data->set('params', $params);

   * Get data from Drupal's temp_store.
   * @return array
  public function getMyDataInTempStore() {
    // Get tempstore service.
    $tempstore = \Drupal::service('tempstore.private');
    // Get tempstore data we need.
    $tempstore_data = $tempstore->get('my_custom_key');
    $tempstore_params = $tempstore_data->get('params');
    // Get vars.
    $my_var_1 = $tempstore_params['var_1'];
    $my_var_2 = $tempstore_params['var_2'];
    // Return data in array.
    return [
      'var_1' => $my_var_1,
      'var_2' => $my_var_2,
Drupal code Planet Drupal
Written by Joris Snoek | Jun 02, 2021

Join the conversation

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web