Closed (fixed)
Project:
Webform
Version:
7.x-4.x-dev
Component:
Code
Priority:
Normal
Category:
Support request
Assigned:
Unassigned
Reporter:
Created:
3 Apr 2013 at 01:50 UTC
Updated:
30 Jun 2013 at 01:10 UTC
Forgive me if this is a duplicate issue, but I couldn't seem to find the answer.
I am implementing hook_form_alter() in a custom module to add some trickery and some validation based on said trickery. At a certain point, the code goes:
if ($foobar) {
yadayada();
}
else {
drupal_set_message(t('This form was not properly generated. Please select the survey from your school\'s page.'), 'error');
}
Well, for whatever reason, when this error message is triggered, it is appearing twice. I'm curious why, and if I can stop it without using this hack I'm now using, which works, but somehow is embarrasing:
if ($foobar) {
yadayada();
}
else {
// Hack to make the message display only once.
static $message = FALSE;
if (!$message) {
drupal_set_message(t('This form was not properly generated. Please select the survey from your school\'s page.'), 'error');
$message = TRUE;
}
}
Comments
Comment #1
quicksketchPer the documentation, the easiest way to solve this problem is to simply set the 3rd parameter on drupal_set_message() to FALSE. That prevents duplicate messages.
The double-messages can happen easily in hook_form_alter() because forms are always built twice when a form is submitted. Once to build the form before it's submitted, then again when the is rebuilt to show validation errors in place with the fields highlighted. The same thing can happen if you redirect back to the same page after the form is completed, or if the form is a multi-page form. It's always built once for submitting, then a second time for rendering.
An alternative way of avoiding duplicate messages is to check if $form_state['input'] is empty, and only show the message if it's empty. This means that the form is being built the first time and not during a submission.