How to store temporary data in Drupal 9 and Drupal 10

During development of complex UI’s with customized approaches, there will be a  need for storing data for a shorter time before permanently storing to the back end. In this case we have to store  data temporarily for a registered/anonymous user or for a process/ session  for a shorter duration. 

In order to achieve this we are discussing different methods of temporary storage available in Drupal 9 & 10, also the use cases in which each method is more suitable. 

There are three ways we can store data temporarily in Drupal.

  • Using Session
  •  Using Private temp store
  •  Using Public temp store

Storage Using Session 

The Drupal session management subsystem is built on top of the Symphony session component.

A session is only started if necessary and the session cookie is removed from the browser as soon as the session has no data. For this reason it is important for contributed and custom code to remove session data if it is not used anymore.

Session data is accessed via the \Symfony\Component\HttpFoundation\Request::getSession() method, which returns an instance of \Symfony\Component\HttpFoundation\Session\SessionInterface. The most important methods on SessionInterface are set(), get(), and remove().

Some of features of session storage provided below

  • Session is used for small data storage not exceeding a few megabytes.
  • session data is stored in the database table sessions
  • Session data is preloaded in memory, Drupal is not going to request session data each time.


Usage of session 

In procedural way, you can get current session from request as below in form, controller and services.

 $request = \Drupal::request();
 $session = $request->getSession();
 $session->set('student_name', $stud_name);

As mentioned above you can set multiple values using set(‘key’,’value’)  function  to set values in session with a key.

So if you want to retrieve session value use get function as below.

$session = \Drupal::request()->getSession();
$student_name = $session->get('student_name');

get() function receives key as a parameter to retrieve value.

Download sample module here for understanding above procedural way of session usage.

Also we can use dependency injection in controller and forms, refer above sample module.

Details of modules files provided in above sample module page.

Use below line for avoiding caching of the form if you want to load session data in build function of the form.

$form[‘#cache’][‘max-age’] = 0;

Session mostly used for Store and retrieve data associated with a user’s browsing session.

Sessions are stored in Session column of session table in database as a serialized object of BLOB data type.

It is important to keep the amount of data stored inside the session to a minimum, as the complete session is loaded on every request.

If you want to store an important amount of data specific to a user’s session, use the Key/Value store to save the serialised data and only store the key to the entry in the session.

Using Tempstore

Temp store used to store data temporarily for a given owner. Here given owner means any user/session/process.

So here we can retain data for a particular time and later we can store data permanently. 

Tempstore can store more amount of data compared to session.

Some of the features of temp stores are provided below.

  • Tempstore data is not preloaded in memory, data loaded  from the database table to memory whenever it is needed.
  • Data stored in key_value and key_value_expire tables.
  • More data can be stored in tempstore since data not pre loaded in memory.

There are two types of tempstore.

  • Private Tempstore
  • Shared Tempstore

A tempstore is for data that needs to be persisted between requests. Similar to session but shared temp store shared between users and sessions are not.

Shared tempstore is shared between users. One of example for shared tempstore is  views configurations, whenever any settings updated in views, a shared tempstore keep the changes, this changes will be available in tempstore until user save the entire views. Before saving all configuration any user can login and change this temporary changes, even same user can see the same changes after log out and log in.

Private tempstore is same like public tempstore, but data not shared between users, so usage of this storage will more in multi step forms and wizard types pages. Here data not shared between anonymous users.

Both the temp store are stored tables key_value and key_value_expire. There will be expiry for both temp store, by default it is 7 days, usage of tempstore mostly preferred for developing complex UI.

The main difference between shared and private temp store is how they use Key/Value collection, Each SharedTempStore belongs to a particular owner (e.g. a user, session, or process). Multiple owners may use the same key/value collection, and the owner is stored along with the key/value pair. In PrivateTempStore all keys are ensured to be unique for a particular user and users can never share data.

Usage of Private temp store

Below code used to set the value of private temp store. As provided below we have to have collection first. Here ‘mymodule’ is the collection. Then on this collection we are calling set function with key and value as parameters.

/** @var \Drupal\Core\TempStore\PrivateTempStore $store */
$store = \Drupal::service('tempstore.private')->get('mymodule');
$store->set('var_name', $data);

to get the data back again just use the get() method.

/** @var \Drupal\Core\TempStore\PrivateTempStore $store */
$store = \Drupal::service('tempstore.private')->get('mymodule');
$data = $store->get('var_name');

There are many predefined functions in tempstore.private service, some of them provided below.

PrivateTempStore::delete  -> Deletes data from the store for a given key and releases the lock on it.

PrivateTempStore::get – > Retrieves a value from this PrivateTempStore for a given key.

PrivateTempStore::getMetadata – >Returns the metadata associated with a particular key/value pair.

PrivateTempStore::getOwner -> Gets the current owner based on the current user or the session ID.

PrivateTempStore::set  -> Stores a particular key/value pair in this PrivateTempStore.

PrivateTempStore::$expire -> The time to live for items in seconds.PrivateTempStore::$currentUser -> The current user.

You can see more functions in this page

Usage of Shared temp store

Same as private tempstore, instead of tempstore.private service, tempstore.shared is used as below.

/** @var \Drupal\Core\TempStore\PrivateTempStore $store */
$store = \Drupal::service('tempstore.shared)->get('mymodule');
$store->set('var_name', $data);

to get the data back again just use the get() method.

/** @var \Drupal\Core\TempStore\PrivateTempStore $store */
$store = \Drupal::service('tempstore.shared)->get('mymodule');
$data = $store->get('var_name');

If the user is not logged in then a session instance is started so that the anonymous user can still have a private store.

Below provided some of important functions in SharedTempstore.

SharedTempStore::$expire -> The time to live for items in seconds.

SharedTempStore::$owner -> The owner key to store along with the data (e.g. a user or session ID).

SharedTempStore::delete -> Deletes data from the store for a given key and releases the lock on it.

SharedTempStore::deleteIfOwner -> Deletes data from the store for a given key and releases the lock on it.

SharedTempStore::get -> Retrieves a value from this SharedTempStore for a given key.

SharedTempStore::getIfOwner -> Retrieves a value from this SharedTempStore for a given key.

You can see more function in this page.

If you want to store data for  anonymous user, always use private temp store. This will make sure all users accessing application/form  at a time have their unique values  stored. In older versions there was an issue  with this private temp store,  where anonymous user data can be seen for other users,  This  issue was due to session start. This issue was resolved in the latest drupal 9 and drupal 10 versions.

Recommended way of using services is using dependency injection.

Read more about dependency injunction here.

See the sample module here for Private  and Shared Tempstore usage. In this module we are doing dependency injunction of tempstore Service.

Details of modules files provided in above sample module page.

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...