删除 drupal 8 中的默认消息

Remove default message in drupal 8

在 Drupal 7 中

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

如何在 drupal 8 中实现这一点? 请帮助

您可以通过不止一种方式解决您的问题。

第一种方式:

您可以在核心用户模块中进行小的改动。 继续:

\core\modules\user\src\RegisterForm.php

在该文件中,您可以更改以下行:

drupal_set_message($this->t('Registration successful. You are now logged in.'));

注意: 这是最简单的方法,但在这种情况下,您将编辑 Drupal 核心模块,这通常是不好的做法。在进一步的开发中,您可能会遇到更新时覆盖您的更改等问题。

第二种方式:

您可以使用模块禁用最终用户消息。 Disable message 模块有您需要的选项。在模块配置中,您有一个文本框,您可以在其中过滤出显示给最终用户的消息。

第三种方式:

Drupal 8 中的消息存储在会话变量中,并通过 $messages 主题变量显示在页面模板中。当你想在调用模板之前修改传递给模板的变量时,你应该使用预处理函数。在您的情况下,您可以在会话变量中搜索字符串并在显示之前 alert/remove 它。

function yourmodule_preprocess_status_messages(&$variables) {

  $message = 'Registration successful. You are now logged in.';
  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {
      if ($type == 'status') {
        $key = array_search($message, $messages);
        if ($key !== FALSE) {
          unset($_SESSION['messages'][$type][$key]);
        }
      }
    }
  }
}

(注:未经测试的代码,谨防错别字)

希望对您有所帮助!

首先,在 Drupal 8 中,消息存储在与以前相同的 $_SESSION['messages'] 变量中。但是,直接使用它并不是一个好方法,因为有drupal_set_message and drupal_get_messages个函数,你可以随意使用。

然后,使用 status-messages 主题显示状态消息。这意味着您可以为它编写预处理函数并在那里进行更改:

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

然而,与 Drupal 7 的主要区别在于,现在状态消息并不总是字符串,它们可能是 Markup class. They are wrappers around strings and may be cast to underlying string using magic method __toString 的对象。这意味着它们可以与字符串进行比较并作为字符串进行比较:

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;
       }
     }
   }
  }
}

阅读the related change record后,我发现了\Drupal::messenger()->deleteAll()。我希望这对某人有用。更新:您不应该这样做,因为它也会删除所有后续消息。相反,做 unset(['_symfony_flashes']['status'][0]).

您可以安装模块 Disable Messages 并在模块配置中按模式过滤消息。

对于这种特殊情况,您可以在模块配置中使用以下模式过滤掉消息

Registration successful.*

虽然问题是围绕不再支持的 Drupal 8 提出的,但该模块适用于 Drupal 7、8、9。