Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove default message in drupal 8

In Drupal 7, I could use the following code.

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

What is the equivalent code for Drupal 8?

like image 895
rishabh318 Avatar asked Aug 05 '16 11:08

rishabh318


1 Answers

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;
       }
     }
   }
  }
}
like image 190
Stanislav Agapov Avatar answered Sep 27 '22 22:09

Stanislav Agapov