Mr Treublaan 1-3
1097 DP Amsterdam
The Netherlands

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

02 Jun, 2021 Drupal

Home Blog How to set and get data w...

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
Let's Talk

Please tell me all about your project!
Mail , or send a message:

Got some more time?

Related content
09 May, 2023 Drupal

Save time, frustration, and potential content loss.


07 Jun, 2021 Drupal

Programmatically in multiple Views


25 May, 2021 Drupal

With new features like: @-mentions, drag-and-drop images & general settings.