Basically the issue is that drupal_set_message is showing the message twice on some pages when it is called from hook_init.

Can someone give some advice about this issue, please ?


It'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';
  • hi Clive, thanks for the answer! So according to you if I add this in the check in hook_init - it must work, but I just checked and it is not working so here is what I wrote in hook_init: if (user_is_logged_in() && !_is_ajax_request() && !have_profile()) { drupal_set_message(...) } – Nikolay Borisov Nov 5 '13 at 14:22
  • Is have_profile() returning the expected value? – Clive Nov 5 '13 at 14:27
  • yes I was just editing my comment ... exactly – Nikolay Borisov Nov 5 '13 at 14:27
  • yes ... everything is working - just it is showing twice sometimes, and when I checked further - I realized that the hook_init is executing twice, because I added a dpm there – Nikolay Borisov Nov 5 '13 at 14:28
  • Hmmm...you can check that it's the definitely happening twice in the same request using a static: 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) – Clive Nov 5 '13 at 14:33

If someone is coming here and looking for a solution to this, the easiest way to get this fixed is with a simple "$repeat = FALSE" (https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_set_message/7)

For example:

drupal_set_message('Please set the Content ID for lala', $msg_type ,$repeat = FALSE);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.