Save user / temporary data on $_SESSION | Drupal 8

Save user / temporary data on $_SESSION

Submitted by editor on Wed, 11/18/2015 - 12:44
Question

How to set and get data using $_SESSION on Drupal 8?

Store data on session.

Example:

$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->set('var_name', $session->get('var_name',0) + 1);
drupal_set_message($session->get('var_name'));

 

This is similar to :
$_SESSION['mymodule']['test'] = "Just for Test";  
$data = $_SESSION['mymodule']['test'];

 

To save data on configuration database.

To set data:
    $session = \Drupal::service('user.private_tempstore')->get('mymodule');
    $session->set('test', "Just for Test");

To get data:
    $session = \Drupal::service('user.private_tempstore')->get('mymodule');
    $data = $session->get('test');

 

Comments

Ojcze Nasz (not verified)

Thu, 04/07/2016 - 16:01

In my project I've also added :

$session->delete('mymodule');

to destroy that data after being retrieved to prevent being reused.

Great stuff, Drupal 8 rulez !

Add new comment