How to display a message in Drupal 9

Messages can be displayed using Drupal Messenger service,

\Drupal::messenger()->addMessage('This is a custom message', 'custom');

\Drupal::messenger()->addError(t('This is an error message, red in color'));

\Drupal::messenger()->addStatus(t('This is a status message, green in color'));

\Drupal::messenger()->addWarning(t('This is a warning message, yellow in color'));

To display messages with dynamic variables value,

\Drupal::messenger()->addStatus(t('Dear %user, Welcome to our %site',['%user' => 'admin', '%site' => 'Drupal Learn']));

Category