Tonight I came this comment from a developer:

Rather than using the DisplayErrors control and showing the error messages, I just want a count.  So I could do something like “You have 4 message(s) on the page”

All error messages can be displayed in a Display Errors control but can also be accessed programmatically, via facesContext.getMessages(). This gives access to a Java Iterator of all error messages passed via validation or programmatically via SSJS or Java.

The problem is there is no getCount() method of an Iterator, so you need to loop through the iterator. That shouldn’t be a problem, unless you’ve got loads of errors. If you’ve got so many required fields that iterating causes a problem, the form is probably too large.

My solution was to add a Computed Field with the following SSJS as the value:

var msgs = facesContext.getMessages();
var count = 0;
while (msgs.hasNext()) {
var obj = msgs.next();
count++;
}
return "You have " + @Text(@Integer(count)) + " message(s) on the page";

Line 1 gets the Messages iterator and line 1 initialises a count. Then comes a loop while there are any error messages. The key is on line 4 to call msgs.next(). Even though the code does nothing with it, if there is no call to get the next error message, the server gets stuck in an infinite loop!

But we don’t want to tell the user they have no messages. So we can set the rendered property to:

facesContext.getMessages().hasNext()

Simple, but very effective.

2 thoughts on “How Many XPages Errors Have I Got?”

    1. You can ignore that, Sorry about that, It would be nice, but it apparently is only written for JSF 2.0 and up. I must have used it in a jsf 2.0 app.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top