Tuesday, October 19, 2010

XPages: Show validation errors for multiple/specified components

There's a lot of great stuff in XPages, but there's also a few things I miss. One of those things is message-controls that you can connect to multiple fields. It's quite easy to emulate this using a little bit of SSJS, and a xp:text.

SSJS:
// Fetch messages for specified components
function getFacesMessages( components ){
try {
if( typeof components !== 'array' && typeof components != 'object' ){ components = [ components ]; }
var clientId, component, messages = [], msgIterator;
for( var i = 0; i < components.length; i++ ){
component = components[i];
if( typeof component === 'string' ){
clientId = getClientId( component );
} else {
clientId = component.getClientId( facesContext );
}

msgIterator = facesContext.getMessages( clientId );
if( !msgIterator ){ continue; }
while( msgIterator.hasNext() ){
messages.push( msgIterator.next().getSummary() );
}
}
return messages;
} catch( e ){ /*Debug.logException( e );*/ }
}

XPages source code example:
<xp:text styleClass="xspMessage" 
escape="false" rendered="#{javascript:return ( this.value );}">
<xp:this.value>
<![CDATA[#{javascript:return getFacesMessages( [ 'field1', 'field2' ] ).join( '<br />' );}]]>
</xp:this.value>
</xp:text>
Share and enjoy!

2 comments:

Thomas Adrian said...

There is an issue with this code. You need to change the 'array' to 'object" in the getFacesMessages function.

Tommys code is useful if you for some reason want to display the validation messages for only some of the validated fields

Tommy Valand said...

I'm pretty certain the code worked when I posted it, but there might have been changes to the API.

I'll update the snippet. Thanks :)