20

I am working on a shop, and for the cart, i need to store items before payment.

  $tempstore = \Drupal::service('user.private_tempstore')->get('boutique');
  $tempstore->set('poids', $form_state->getValue('poids'));

I take a look on the user service for :

pivate_tempstore and shared_tempstore

But that work only for authenticates users.

What can I use for store data ? $_SESSION ? or Drupal 8 has a service for that ?

3
  • I am using cookies. I have identifier and hash cookie that I validate and then pair the identifier with what I need. I don't use sessions because D8 stopped using them for anonymous users as well.
    – user21641
    Commented Apr 11, 2016 at 10:15
  • Ok and why you don't use $_SESSION ?
    – Kevin
    Commented Apr 11, 2016 at 10:20
  • drupal.org/node/2935639
    – JFC
    Commented Jan 24, 2019 at 21:07

6 Answers 6

16

In Drupal 8 the session variables can be accessed off the request:

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

If you want to set something in the session, you can do the following:

$profile = 'Person';
$session->set('profile', $profile);

Or to retrieve a session variable:

$details = $session->get('profile');
5
  • 2
    i ll give it a try, so you can store an array ?
    – Kevin
    Commented Sep 20, 2017 at 11:01
  • 2
    Yes you can store an array, I changed my code to align with the question, but mine is actually storing an array.
    – Duncanmoo
    Commented Sep 22, 2017 at 8:18
  • 4
    Struggled to get other solutions working - this is so simple and seems to actually work
    – Nate
    Commented Dec 13, 2017 at 17:13
  • 2
    how to delete a session variable?
    – siddiq
    Commented Jun 25, 2018 at 3:05
  • 1
    Thank that work perfectly
    – Kevin
    Commented Jun 12, 2019 at 21:16
22

Late answering, but it's worth mentioning that you can use private tempstore for anonymous users, as long as the tempstore has access to an active session. To do so, you need to inject your class with services for the temp store, session, and current user, like so:

public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;

    $this->store = $this->tempStoreFactory->get('myclass.storename');
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('user.private_tempstore'),
        $container->get('session_manager'),
        $container->get('current_user')
    );
}

Then you just need to ensure you start the session manager if the user is anonymous, before you need to put anything in the temp store:

if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
    $_SESSION['session_started'] = true;
    $this->sessionManager->start();
}

You might find this approach preferable because it means that you can use a single system for temporary storage, regardless of whether a user is logged in.

(My code examples are lifted more-or-less verbatim from this excellent tutorial on building multi-step forms.)

3
6

A session can be anonymous (uid=0). You can simply use $_SESSION and drupal will take care of this.

Store session data:

$_SESSION['mymodule']['variablename'] = $tempdata;

Get session data:

$tempdata = $_SESSION['mymodule']['variablename'];

Update 1: Session Object

While there is still work going on in D8 core, see this issue Convert uses of $_SESSION to symfony session retrieved from the request, you can use the session object in the request to store session data. But don't mix it, data you store with one of these methods is not available in the other. See this answer for more details Drupal 8 and Session Management:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

Update 2: TempStore

The TempStore seems to be very popular in D8. But it's too complicated to store some values like in this question. It is intended for big chunks of data like for example preview data or unsaved Views. Here are the official change records:

Access session data through the Request object

TempStore API added for persistent, expirable storage of non-cache data

2
  • yes session can be anonymous but not for the user service apparently.
    – Kevin
    Commented Apr 11, 2016 at 10:07
  • In Drupal 8 best practice would dictate that you should use an Interface to read and write data to session variables. This allows for swappable storage and a brighter future.
    – George
    Commented Apr 11, 2017 at 16:26
3

The $this->sessionManager->start(); was not working anymore for me because of the last update. I changed it in to $this->sessionManager->regenerate();

2
  • You should add this as a comment to the original answer rather than as a new answer Commented Aug 11, 2019 at 16:40
  • 2
    @wranvaud , I had not enough reputation to be able to comment on another answer. Commented Aug 14, 2019 at 8:49
2

I wrote this module to solve this problem in a generic way. https://www.drupal.org/project/anonymoussession

use this code before using the session, and you application works for both known and unknown visitors.

$anonymousSession = \Drupal::service('anonymoussession');
$anonymousSession->apply();

$_SESSION[.... 
1

Since the Saving to the private tempstore doesn't start a session for anonymous users has been resolved in Drupal core, the private tempstore now works for anonymous users.

Not the answer you're looking for? Browse other questions tagged or ask your own question.