Basically the issue is that drupal_set_message()
shows a message twice on some pages, when it is called from hook_init()
.
How can I avoid it happens?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIt's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.
To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.
It happens because hook_init()
is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.
For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:
function is_ajax_request() {
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (user_is_logged_in() && !_is_ajax_request() && !have_profile()) { drupal_set_message(...) }
Nov 5, 2013 at 14:22
static $foo = FALSE; if (!$foo) { $foo = TRUE; drupal_set_message('..); }
. If you only get one message from now on, then hook_init()
is indeed being invoked twice. If not, it's that the message is being added to the session as part of another page request somehow (and usually that's AJAX)
The easiest way to avoid the messages are repeated is setting the drupal_set_message()
$repeat
parameter to FALSE
.
drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'), 'status', FALSE);