I would like to programmatically set a message shown at least once for selected users or for all users with a specific role.
-
Do you prefer a back-end solution? Have you considered implementing this as a front-end library? this is an open source project, demo here. If this is a viable solution then the question would become "how to attach a library to specific users?" and the answer is well documented theme.api.php hook_page_attachments(array &$attachments)– Cesar MooreAug 28, 2018 at 22:05
-
I've great success with this: drupal.org/project/disable_messages– BeauAug 29, 2018 at 23:46
1 Answer
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();
$messenger->addMessage($message);
$session->set('mymodule_message_was_displayed', TRUE);
}
}