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?
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;
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With