Clearing Individual Form Messages

Adding a form message to the top of the form is easy enough by using the g_form.addErrorMessage or g_form.addInfoMessage functions. Then getting rid of them is again, another simple call of g_form.clearMessages() which does what the name implies and removes them all.

My scenario where this didn’t work so well was where I was adding a form error message on a particular action and if they kept doing that mistake, it kept adding a form error message. The obvious thing to do therefore was to use clearMessages() before each addErrorMessage but it was removing form messages which I didn’t want to be removed.

Turns out ServiceNow have a hidden argument to addErrorMessage/addInfoMessage to set a html ID to the field.

I could then identify and remove this individual field from list of messages without any issues.

So the code became:

$j('#myErrorMessage').remove();
g_form.addErrorMessage('You cant do that!', 'myErrorMessage');

This would automatically remove the error message if it could find it already exists, and then re-add it again. Or you can check if it exists and only add if it doesn’t:

if (!$j('#myErrorMessage')) {
g_form.addErrorMessage('You cant do that!', 'myErrorMessage');
}

Choice is yours depending on your code (I had scenarios for each), but there you go. A simple out of the box method to identifying form messages.

As for why they’re not documented on the wiki is probably due to the fact that removing them still requires DOM manipulation and $j/$/document.getElementById/gel (whichever you prefer using), and ServiceNow actively discourage using those functions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s