Question

I am updated one of my Drupal 7 modules for Drupal 8 and I discovered that I need to use PrivateTempStore rather than $_SESSION variables. I followed some great examples online, but it does not seem to be storing the data correctly. I am even checking the database directly afterwards, but it does not have the correct data. I've done some debugging at the point where I am storing the data to see what is set, and it says it is set with the value I expect. However, the database does not show this value and reloading the page and outputting the value retrieved does not show what I expect. What are the method people use to debug these issues.

Currently running Drupal 8.8.1 on PHP 7.3.

Was it helpful?

Solution

I am updated one of my Drupal 7 modules for Drupal 8 and I discovered that I need to use PrivateTempStore rather than $_SESSION variables.

The Drupal 8 replacement for $_SESSION is not PrivateTempStore, it is the session object in the request:

Drupal 7:

function mymodule_session_counter_increment() {
  if (!isset($_SESSION['mymodule_count'])) {
    $_SESSION['mymodule_count'] = 0;
  }

  return $_SESSION['mymodule_count']++;
}

Drupal 8:

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

    return $value;
  }
}

See the change record: https://www.drupal.org/node/2380327

For more info see this topic: How do I store the values submitted in a form in the session?

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top