I want to save my data in a session: under drupal 8.6

I worked with "Private tempstore" it works locally but not in the server prod only if user is anonymous.

if ($this->currentUser->isAnonymous()) {

The same for the native php session.

I ask if it can be stored with php configuration or how?

thank you


Don't use procedural code. Session is now a Symfony object:

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

    return $value;

Source: https://www.drupal.org/node/2380327


What you need to do for debugging depends on your dev environment. If for example you have disabled caching you are not able to debug caching issues. In this case enable caching in dev and see what happens if you add cache metadata to the returned result:

    return [
      '#markup' => $value,
      '#cache' => ['max-age' => 0],

Cache max-age = 0, because the result in this example changes on each request and is not worth caching.

When this is working the next step is to optimize production performance. Put the code in a #lazy_builder callback or in a block, which is built lazily by default. In both cases this is then auto-placeholdered for certain cache condition like cache max-age = 0, so that the rest of the page can still be cached.

  • That doesn't work, I use Drupal 8.6 not Drupal 8.0 – triki hajer Mar 27 '19 at 13:28
  • This code example works only in a controller (for any D8 version). If you want to get the request in other places you need to adjust the first line. Where is your code placed? – 4k4 Mar 27 '19 at 13:56
  • it placed in controller, that work in my local environnement but not for prod – triki hajer Mar 27 '19 at 14:09
  • I don't know what you mean, the referenced change record is for production code. – 4k4 Mar 27 '19 at 14:33
  • It seems likely that there is some other difference making it fail in production vs. development. – greggles Mar 27 '19 at 14:40

that also can be resolved with this code in rending controller :

$output = [];

$output['#cache']['max-age'] = 0;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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