12

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 ?

  • 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 Apr 11 '16 at 10:15
  • Ok and why you don't use $_SESSION ? – Kevin Apr 11 '16 at 10:20
  • drupal.org/node/2935639 – JF Kiwad Jan 24 at 21:07
11

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

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

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

  • yes session can be anonymous but not for the user service apparently. – Kevin Apr 11 '16 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 Apr 11 '17 at 16:26
1

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

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

protected by Community Dec 1 '17 at 8:58

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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