I would like to programmatically set a message shown at least once for selected users or for all users with a specific role.


1 Answer 1


Copy the following snippet to your module, then you have to replace MODULE with your module machine name

 * Implements hook_preprocess_HOOK().
function MODULE_preprocess_page(&$variables) {
  $message = t("You have been served!");
        $request = \Drupal::request();
  $session = $request->getSession();
  $message_was_displayed = $session->get('mymodule_message_was_displayed', FALSE);
  if ($message_was_displayed === FALSE) {
    $messenger = \Drupal::messenger();
    $session->set('mymodule_message_was_displayed', TRUE);

Your Answer

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

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