Skip to main content
Hide and override drupal status messages

Hide and override drupal status messages

      This blog describes how to hide and override drupal status messages while creating and editing nodes.

      When you create or edit the nodes, drupal displays status messages like 'node has been created' and 'node has been updated'. Some may not be interested to view these messages. You can hide these messages using drupal_get_messages(). It returns all messages that have been set using drupal_set_message(). You need to add it to a custom submit handler for the corresponding form. You can add custom submit handler using either hook_form_alter() or hook_form_form_id_alter() in drupal. 

       To hide drupal status messages, use the code below. For example, i have hidden the status messages only for article node form.

<?php
/**
 * Implement hook_form_alter()
 */
function kf_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    // to add custom submit handler
    $form['actions']['submit']['#submit'][] = 'kf_article_form_submit';
  }
}

/**
 * Implement kf_article_form_submit
 */
function kf_article_form_submit($form, &$form_state) {
  // to hide drupal status messages
  drupal_get_messages('status');
}
?>

       Similarly you can override these status messages. For that, you need to add messages after drupal_get_messages() in the custom submit handler.

<?php
/**
 * Implement kf_article_form_submit
 */
function kf_article_form_submit($form, &$form_state) {
  // to hide drupal status messages
  drupal_get_messages('status');
  // to override druapl status message
  drupal_set_message(t('Your message..!'));
}
?>

      Now you can get drupal status messages. Similarly you can hide and override the drupal status messages for other node forms as well.

 

Comments

This does risk removing other potentially important messages when you intend to remove a specific message.

A slightly improved option would be to loop through the response of drupal_get_messages('status'), and test each item to see if it's text matches the string you're looking for. If not then run it back through drupal_set_message() to re-add it to the messages.

Thx to Paul Querol for the suggestion, I was able to render manually a warning message by doing this:

// Save current warning messages, provide default to prevent empty value.
$messages_backup = drupal_get_messages('warning') + array('warning' => array());
// Generate new warning message, to be rendered inside the form.
drupal_set_message(t('Some warning!'), 'warning');
$form['warning_message'] = array(
'#type' => 'markup',
'#markup' => theme('status_messages', array('display' => 'warning')),
);

// Restore previous warning messages.
foreach ($messages_backup['warning'] as $message) {
drupal_set_message($message, 'warning');
}