'Remove default message in drupal 8

In Drupal 7

if ($_SESSION['messages']['status'][0] == t('Registration successful. You are now logged in.')) {
    unset($_SESSION['messages']['status']);
  }

How can I achieve this in drupal 8? Please help



Solution 1:[1]

First of all, in Drupal 8, messages are stored in the same $_SESSION['messages'] variable as before. However, using it directly is not a good way, as there exist drupal_set_message and drupal_get_messages functions, which you may freely use.

Then, status messages are shown using status-messages theme. This means that you can write preprocess function for it and make your alteration there:

function mymodule_preprocess_status_messages(&$variables) {
  $status_messages = $variables['message_list']['status'];
  // Search for your message in $status_messages array and remove it.
}

The main difference with Drupal 7, however, is that now status messages are not always strings, they may be objects of Markup class. They are wrappers around strings and may be cast to underlying string using magic method __toString. This means that they can be compared with and as strings:

function mymodule_preprocess_status_messages(&$variables) {
  if(isset($variables['message_list']['status'])){
   $status_messages = $variables['message_list']['status'];

   foreach($status_messages as $delta => $message) {
     if ($message instanceof \Drupal\Component\Render\MarkupInterface) {
       if ((string) $message == (string) t("Searched text")) {
         unset($status_messages[$delta]);
         break;
       }
     }
   }
  }
}

Solution 2:[2]

Upon reading the related change record, I have discovered \Drupal::messenger()->deleteAll(). I hope this is useful to someone. UPDATE: You should NOT do this, as it removes all subsequent messages as well. Instead, do unset(['_symfony_flashes']['status'][0]).

Solution 3:[3]

You can install the module Disable Messages and filter out messages by pattern in the configuration of the module.

For this particular case, you can filter out the message using the following pattern in the module configuration

Registration successful.*

Although the question is asked around Drupal 8 which is no longer supported, the module works for Drupal 7, 8, 9.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3 anoopjohn