0

I created a custom module that allows users to enter their information, and during the form submission, I set a session with the name that they type in the form:

$session = \Drupal::request()->getSession();
$session->remove('contact_first_name');
$session->set('contact_first_name', $form_state->getValue('first_name'));

Next, I set the name as a variable to be used on another page that I created as a thank you.

mytheme.theme:

function scottishleader_preprocess_page(&$variables) {
    $variables['signupname'] = \Drupal::request()->getSession()->get('contact_first_name');
}

Inside a template, I am now able to use the "signupname" as a variable.

But now I noticed that if the user goes back to the form and enters different detail, after the submission, the signupname" variable still return the name of the previous session.

Question: How can I delete or empty this specific session before the form gets submitted?

NOTE: I cannot destroy all the sessions because there is a session that must always be kept alive.

4
  • 3
    Possible duplicate of How can I destroy or unset session?
    – No Sssweat
    Nov 21, 2019 at 17:32
  • @NoSssweat the question is not exactly a duplicate because the answer does not work for me. Nov 21, 2019 at 17:46
  • It's due to caching. Not session related.
    – No Sssweat
    Nov 21, 2019 at 18:13
  • Yes, try to display the session variable in a block with a cache context: $build['#cache']['contexts'] = ['session'];
    – 4uk4
    Nov 21, 2019 at 19:08

0

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.

Browse other questions tagged or ask your own question.