0

After my user is submitting a form, I want to logged him out, then redirect to the front page. then, display a message.

public function submitForm(array &$form, FormStateInterface $form_state) {
  /**
   * my logic
   **/
  if ($isDeleted) {
    $this->messenger()->addMessage('Logged out');
    user_logout();
    $home = \Drupal\Core\Url::fromRoute('<front>')->setAbsolute();
    $form_state->setRedirectUrl($home);
  }
}

This code works fine, but the message doesn't show up. I read/assumed that the messenger is linked to the current session, so by log out the user, the messenger is destroyed.

So I tried to create another messenger after the user logout, but still, the message isn't displayed.

6
  • Might seem obvious but is the "Status messages" block definitely set to show on your homepage? Do other messages display on your homepage ok? Commented Dec 2, 2022 at 11:18
  • Yes, if I remove the "user_logout()" function, the message works (so the block works)
    – lobafox
    Commented Dec 2, 2022 at 11:20
  • Yes you're probably right the messages are stored via the session which is cleared on logout. Have you tried switching the position in the code of the user_logout() and the message setting? A possible alternative is you redirect to the homepage with a url parameter e.g. ?user_logged_out and then use some JS or something to create/show a message Commented Dec 2, 2022 at 11:25
  • yes, I tried to switch the code, no changes. I'd like to avoid to add parameters to the url (at the last resort, I'll probably do it)
    – lobafox
    Commented Dec 2, 2022 at 14:06
  • 1
    There's a core issue related to this. drupal.org/project/drupal/issues/754560
    – imclean
    Commented Dec 6, 2022 at 0:39

0

Your Answer

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

Browse other questions tagged or ask your own question.