1

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()) {
  session_start();
}

The same for the native php session.

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

thank you

2 Answers 2

2

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

Edit:

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.

7
  • That doesn't work, I use Drupal 8.6 not Drupal 8.0 Mar 27, 2019 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?
    – 4uk4
    Mar 27, 2019 at 13:56
  • it placed in controller, that work in my local environnement but not for prod Mar 27, 2019 at 14:09
  • I don't know what you mean, the referenced change record is for production code.
    – 4uk4
    Mar 27, 2019 at 14:33
  • It seems likely that there is some other difference making it fail in production vs. development.
    – greggles
    Mar 27, 2019 at 14:40
0

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

$output = [];

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

https://www.drupal8.ovh/en/tutoriels/340/disable-cache-for-a-specific-page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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